haveThree([3, 1, 3, 1, 3]) → true
haveThree([3, 1, 3, 3]) → false
haveThree([3, 4, 3, 3, 4]) → false
Answer 1:
public boolean haveThree(int[] nums) {Answer 2:
int count3 = 0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3){
count3++;
if(i<nums.length-1 && nums[i+1]==3)return false;
}
}
return count3==3;
}
public boolean haveThree(int[] nums) {Reference
int count = 0;
boolean found = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 3)
found = false;
if (nums[i] == 3 && found == true)
return false;
if (nums[i] == 3 && found == false) {
found = true;
count++;
}
}
if (count == 3)
return true;
else
return false;
}
http://www.javaproblems.com/2013/11/java-array-2-havethree-codingbat.html
No comments :
Post a Comment