has22([1, 2, 2]) → true
has22([1, 2, 1, 2]) → false
has22([2, 1, 2]) → false
Answer 1:
public boolean has22(int[] nums) {
for(int i=0;i<nums.length;i++){
if(i-1>=0){
if(nums[i]==2 && nums[i-1]==2) return true;
}
}
return false;
}
Answer 2:
public boolean has22(int[] nums) {
boolean found = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 2 && i > 0 && nums[i-1] == 2) {
found = true;
}
if (nums[i] == 2 && i < nums.length-1 && nums[i+1] == 2) {
found = true;
}
}
return found;
}
No comments :
Post a Comment