The for-each
loop hides the iterator (or index here), so you can't get the current value and check the next value at the same time. Use a standard loop. Also, since you don't access any field's - you could make the method static
. Like,
public static boolean unlucky1(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 1 && nums[i + 1] == 3) {
return true;
}
}
return false;
}
And, in Java 8+, you could express that with an IntStream
and anyMatch
like
public static boolean unlucky1(int[] nums) {
return IntStream.range(0, nums.length - 1)
.anyMatch(i -> nums[i] == 1 && nums[i + 1] == 3);
}
Note the nums.length - 1
in both cases, that is to ensure the nums[i + 1]
doesn't exceed the length
of the nums
array on the conditional check.
Updated because you did not add the next condition - which was
in the first 2 or last 2 positions in the array.
That checker is strict. Follow the instructions carefully. I get (working)
public boolean unlucky1(int[] nums) {
int len = (nums == null) ? 0 : nums.length;
for (int i = 0; i < 2 && i + 1 < len; i++) {
if (nums[i] == 1 && nums[i + 1] == 3) {
return true;
}
}
if (len - 2 <= 0) {
return false;
}
for (int i = len - 2; i + 1 < len; i++) {
if (nums[i] == 1 && nums[i + 1] == 3) {
return true;
}
}
return false;
}
Which you could also implement without loops at all, like
public boolean unlucky1(int[] nums) {
int len = (nums != null) ? nums.length : 0;
if (len < 2) {
return false;
}
if ((nums[0] == 1 && nums[1] == 3) || (nums[1] == 1 && nums[2] == 3)) {
return true;
}
return len > 3 && ((nums[len - 4] == 1 && nums[len - 3] == 3) //
|| (nums[len - 2] == 1 && nums[len - 1] == 3));
}
I swapped the ternary order, but that's not important.