Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other.
haveThree([3, 1, 3, 1, 3]) → true
haveThree([3, 1, 3, 3]) → false
haveThree([3, 4, 3, 3, 4]) → false
Solution1:
public boolean haveThree(int[] nums) {
boolean lastIs3 = false;
int count = 0;
for(int i=0; i<nums.length; i++ ) {
if(nums[i]==3 ) {
if(lastIs3) {
return false;
}
lastIs3 = true;
count++;
} else {
lastIs3 = false;
}
}
if(count == 3) {
return true;
}
return false;
}
Solution2:
public boolean haveThree(int[] nums) {
String num = Arrays.toString(nums);
if(!num.contains("3, 3") && count3(nums) == 3 ){
return true;
}
return false;
}
public int count3 (int[] nums) {
int count = 0;
for (int val:nums) {
if(val == 3) {
count++;
}
}
return count;
}