Skip to content

Commit 822e5a2

Browse files
authored
Update Monotonic Array.java
1 parent 167f3df commit 822e5a2

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

Easy/Monotonic Array.java

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
class Solution {
22
public boolean isMonotonic(int[] nums) {
3-
if (nums.length < 2) {
4-
return true;
5-
}
6-
Boolean increasing = null;
7-
for (int i = 1; i < nums.length; i++) {
8-
if (nums[i] == nums[i - 1] && increasing == null) {
9-
continue;
3+
int idx = 0;
4+
int sign = 0;
5+
while (idx < nums.length - 1 && sign == 0) {
6+
if (nums[idx] < nums[idx + 1]) {
7+
sign = 1;
8+
} else if (nums[idx] > nums[idx + 1]) {
9+
sign = -1;
1010
}
11-
increasing = increasing == null ? nums[i] > nums[i - 1] : increasing;
12-
if ((nums[i] > nums[i - 1] && !increasing) || (nums[i] < nums[i - 1] && increasing)) {
11+
idx++;
12+
}
13+
while (idx < nums.length - 1) {
14+
if ((sign == 1 && nums[idx] > nums[idx + 1]) || (sign == -1 && nums[idx] < nums[idx + 1])) {
1315
return false;
1416
}
17+
idx++;
1518
}
1619
return true;
1720
}

0 commit comments

Comments
 (0)