Given an array of ints, return true if every 2 that appears in the array is next to another 2.
twoTwo([4, 2, 2, 3]) → true
twoTwo([2, 2, 4]) → true
twoTwo([2, 2, 4, 2]) → false
Solution:
public boolean twoTwo(int[] nums) {
boolean first2 = false;
boolean lastIs2 = false;
for(int val : nums) {
if(val == 2) {
if (lastIs2 == false && first2 == false ) {
first2 = true;
} else {
first2 = false;
}
lastIs2 = true;
} else {
if(first2 == true) {
return false;
}
lastIs2 = false;
}
}
if(lastIs2 && first2) {
return false;
}
return true;
}