- This question made me deeply aware of how poor my understanding of arrays is, and kneeled. Questions that were taken a month ago have been re-written and it took two hours to solve them. Am I getting more and more useless.
Idea: We must consider which position to cycle to! Neither the array subscripts out of bounds, but also a solution that satisfies the meaning of the problem.
If you think about it calmly, this question is actually very simple. The title says, there are three in a row, so is there any way we can count three at a time and still ensure that the subscript does not cross the boundary?
We can start looping from the number whose subscript is 2 (that is, the third number), and then use if to determine whether it is an odd number before it. Or you can shorten the range of i to less than arr.length-2.
Writing one:
public boolean threeConsecutiveOdds(int[] arr) {
for (int i = 2; i < arr.length; i++) {
if (arr[i] % 2 != 0 && arr[i - 1] % 2 != 0 && arr[i - 2] % 2 != 0) {
return true;
}
}
return false;
}
Writing method two:
public boolean threeConsecutiveOdds(int[] arr) {
for (int i = 0; i < arr.length - 2; i++) {
OUT: for (int j = i + 1; j < arr.length - 1; j++) {
for (int k = j + 1; k < arr.length; k++) {
if (arr[i] % 2 != 0 && arr[j] % 2 != 0 && arr[k] % 2 != 0) {
return true;
} else {
break OUT;
}
}
}
}
return false;
}
Update:
My goodness, I will practice again every other day. I thought about it for a long time. I couldn't remember what method I used before, so I made another way of writing it myself. Although it was past, I felt that I was mentally retarded again when I read what was written earlier.
public boolean threeConsecutiveOdds(int[] arr) {
boolean[] flag1 = new boolean[arr.length];
int count = 0;
for (int i = 0; i < arr.length - 2; i++) {
for (int j = i; j < i + 3; j++) {
if (arr[j] % 2 != 0) {
count++;
}
}
if (count >= 3) {
flag1[i] = true;
}
count = 0;
}
for (boolean i : flag1) {
if (i == true) {
return true;
}
}
return false;
}