Problem:
We'll say that a value is "everywhere" in an array if for every pair of adjacent elements in the array, at least one of the pair is that value. Return true if the given value is everywhere in the array.
isEverywhere({1, 2, 1, 3}, 1) → true
isEverywhere({1, 2, 1, 3}, 2) → false
isEverywhere({1, 2, 1, 3, 4}, 1) → false
Solution:
public boolean isEverywhere(int[] nums, int val) { boolean result = true; for (int i = 0; i <=nums.length-2;i++) { if ( nums[i] != val && nums[i+1] != val) result = false; } return result; }
the length is actually -1 not -2
ReplyDeletenot if you use <= instead of <
Deletepublic boolean isEverywhere(int[] nums, int val) {
ReplyDeletefor(int i=0;i<nums.length-1;i++)
{
if(nums[i]!=val&&nums[i+1]!=val)
return false;
}
return true;
}
for (int i = 0; i <=nums.length-2;i++)
Deleteand
for(int i=0;i<nums.length-1;i++)
is the same thing if you look closely.
why for this 2 expected results:
ReplyDeleteisEverywhere([3], 1) → true
isEverywhere([], 1) → true
result should be true? is it correct?
technically there are no pairs so it is present in every pair. Also the for loop does not work for these cases so it simplifies the desired code for an easy problem like an Array-2
Deletepublic boolean isEverywhere(int[] nums, int val) {
ReplyDeletefor(int i = 0; i < nums.length - 1; i++) {
if(nums[i] == val || nums[i + 1] == val);
else return false;
}
return true;
}
Look how many lines did it take to get solve for me))
ReplyDeletepublic static boolean isEverywhere(int[] nums, int val) {
boolean isEveryWhere = true;
if(nums.length==0 || nums.length==1){
return true;
}
if(nums[0]!=val && nums[1]!=val){
isEveryWhere = false;
}
if(nums[0]==val){
for(int i=0; i<nums.length; i+=2){
if(nums[i]!=val){
isEveryWhere = false;
}
}
}
if(nums[1]==val){
for(int i=1; i<nums.length; i+=2){
if(nums[i]!=val){
isEveryWhere = false;
}
}
}
return isEveryWhere;
}
public boolean isEverywhere(int[] nums, int val) {
ReplyDeleteint len = nums.length;
if(len < 2) return true;
boolean res = false;
for(int i = 0; i<nums.length-1; i++){
if(nums[i] == val || nums[i+1] == val){
res = true;
}else {
return false;
}
}
return res;
}
public boolean isEverywhere(int[] nums, int val) {
ReplyDeleteint len = nums.length;
if(len < 2) return true;
boolean res = false;
for(int i = 0; i<nums.length-1; i++){
if(nums[i] == val || nums[i+1] == val){
res = true;
}else {
return false;
}
}
return res;
}
public boolean isEverywhere(int[] nums, int val) {
ReplyDeleteif (nums.length<2) return true;
int cnt=0;
if (nums[0]==val) cnt=0;
else if (nums[1]==val) cnt=1;
else return false;
boolean stop=true;
for(int i=cnt; i<nums.length; i+=2){
if(nums[i]==val && stop) stop=true;
else return false;
}
return stop;
}