You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/com/fishercoder/solutions/_581.java
+32Lines changed: 32 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -34,6 +34,38 @@ public int findUnsortedSubarray(int[] nums) {
34
34
}
35
35
36
36
publicstaticclassSolution2 {
37
+
/**
38
+
* Time: O(n)
39
+
* Space: O(1)
40
+
* <p>
41
+
* This is just an alternative way of writing Solution1, credit: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/discuss/103057/Java-O(n)-Time-O(1)-Space/106306
42
+
*
43
+
* But still, initializing end to be -2 is an art to take care of the corner case as in Solution1.
44
+
*/
45
+
publicintfindUnsortedSubarray(int[] nums) {
46
+
intend = -2;
47
+
intmax = Integer.MIN_VALUE;
48
+
//go from left to right, find the number that is smaller than the max number on its left side, that should be the end index because it needs to be sorted
49
+
for (inti = 0; i < nums.length; i++) {
50
+
max = Math.max(max, nums[i]);
51
+
if (nums[i] < max) {
52
+
end = i;
53
+
}
54
+
}
55
+
intstart = -1;
56
+
intmin = Integer.MAX_VALUE;
57
+
//go from right to left, find the number that is bigger than the min number on its right, that should be the beginning index
0 commit comments