Skip to content

Commit a6583d0

Browse files
refactor 581
1 parent 4b2394d commit a6583d0

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/main/java/com/fishercoder/solutions/_581.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,38 @@ public int findUnsortedSubarray(int[] nums) {
3434
}
3535

3636
public static class Solution2 {
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+
public int findUnsortedSubarray(int[] nums) {
46+
int end = -2;
47+
int max = 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 (int i = 0; i < nums.length; i++) {
50+
max = Math.max(max, nums[i]);
51+
if (nums[i] < max) {
52+
end = i;
53+
}
54+
}
55+
int start = -1;
56+
int min = 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
58+
for (int i = nums.length - 1; i >= 0; i--) {
59+
min = Math.min(min, nums[i]);
60+
if (nums[i] > min) {
61+
start = i;
62+
}
63+
}
64+
return end - start + 1;
65+
}
66+
}
67+
68+
public static class Solution3 {
3769
/**
3870
* Time: O(nlogn)
3971
* Space: O(n)

src/test/java/com/fishercoder/_581Test.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@
99
public class _581Test {
1010
private static _581.Solution1 solution1;
1111
private static _581.Solution2 solution2;
12+
private static _581.Solution3 solution3;
1213
private static int[] nums;
1314

1415
@BeforeClass
1516
public static void setup() {
1617
solution1 = new _581.Solution1();
1718
solution2 = new _581.Solution2();
19+
solution3 = new _581.Solution3();
1820
}
1921

2022
@Test

0 commit comments

Comments
 (0)