Skip to content

Commit 0cb7779

Browse files
authored
Update Monotonic Array.java
1 parent 866f095 commit 0cb7779

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

Easy/Monotonic Array.java

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
11
class Solution {
2-
public boolean isMonotonic(int[] nums) {
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;
10-
}
11-
idx++;
2+
public boolean isMonotonic(int[] nums) {
3+
int idx = 0;
4+
while (idx + 1 < nums.length && nums[idx] == nums[idx + 1]) {
5+
idx++;
6+
}
7+
boolean increasing = idx + 1 < nums.length && nums[idx] < nums[idx + 1];
8+
while (idx + 1 < nums.length) {
9+
if (nums[idx] > nums[idx + 1] && increasing) {
10+
return false;
11+
}
12+
if (nums[idx] < nums[idx + 1] && !increasing) {
13+
return false;
14+
}
15+
idx++;
16+
}
17+
return true;
1218
}
13-
while (idx < nums.length - 1) {
14-
if ((sign == 1 && nums[idx] > nums[idx + 1]) || (sign == -1 && nums[idx] < nums[idx + 1])) {
15-
return false;
16-
}
17-
idx++;
18-
}
19-
return true;
20-
}
2119
}

0 commit comments

Comments
 (0)