在这个问题中 如果对于数组中的每一对相邻元素,至少有一个是该值,则值在数组中“无处不在”。如果给定值在数组中无处不在,则返回 true。
isEverywhere({1, 2, 1, 3}, 1) → true,因为 1 存在于 (1,2) 和 (1,3) 中
isEverywhere({1, 2, 1, 3}, 2) → false,因为 2 在 (1,2) 但不在 (1,3) 中
isEverywhere({1, 2, 1, 3, 4}, 1) → false,因为 1 出现在 2 对 (1,2) 和 (1,3) 中,但 4 没有一对 1
我的部分工作代码如下,你能帮我解决这个问题吗,卡了好久。
::代码::
public boolean isEverywhere(int[] nums, int val) {
boolean flag = false;
for(int i=0;i<nums.length;i++){
for(int j=i+2;j<nums.length;j++){
if(nums[i] == nums[j]){
flag = true;
}
}
}
return flag;
}
预期结果:
`Expected` `This` `Run`
isEverywhere({1, 2, 1, 3}, 1) → true true OK
isEverywhere({1, 2, 1, 3}, 2) → false true X
isEverywhere({1, 2, 1, 3, 4}, 1) → 假真 X
最佳答案
试试这个:
boolean isEverywhere(int[] nums, int val) {
// use i+=2 to get start index of pair.
for(int i=0;i<nums.length;i+=2) {
// other index in the pair.
int j = i + 1;
// make sure the other index really exists.
if(j < nums.length) {
// if it exists..and val is not equal to
// either in the pair..return false.
if(nums[i] != val && nums[j] != val) {
return false;
}
} else {
// no pair..one element case.
// return true if that element is val..else return false.
return nums[i] == val;
}
}
// array has no unpaired element..and all pairs have val.
return true;
}
关于java - Java 中的数组 - Core Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4502849/