File tree 1 file changed +18
-30
lines changed
1 file changed +18
-30
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public int findUnsortedSubarray (int [] nums ) {
3
-
4
- int [] copy = new int [nums .length ];
5
- for (int i =0 ;i <nums .length ;i ++) {
6
- copy [i ] = nums [i ];
7
- }
8
-
9
- Arrays .sort (nums );
10
- int start = 0 ;
11
- int end = nums .length -1 ;
12
- int ans = 0 ;
13
-
14
- while (start <end ) {
15
- if (nums [start ] != copy [start ] && nums [end ] != copy [end ]) {
16
- ans = end -start +1 ;
17
- break ;
18
- }
19
- else if (nums [start ] == copy [start ] && nums [end ] != copy [end ]) {
20
- start ++;
21
- }
22
- else if (nums [start ] != copy [start ] && nums [end ] == copy [end ]) {
23
- end --;
24
- }
25
- else if (nums [start ] == copy [start ] && nums [end ] == copy [end ]) {
26
- end --;
27
- start ++;
28
- }
29
- }
30
-
31
- return ans ;
2
+ public int findUnsortedSubarray (int [] nums ) {
3
+ Stack <Integer > stack = new Stack <>();
4
+ int start = nums .length ;
5
+ for (int i = 0 ; i < nums .length ; i ++) {
6
+ while (!stack .isEmpty () && nums [stack .peek ()] > nums [i ]) {
7
+ start = Math .min (start , stack .pop ());
8
+ }
9
+ stack .push (i );
32
10
}
11
+ stack .clear ();
12
+ int end = 0 ;
13
+ for (int i = nums .length - 1 ; i >= 0 ; i --) {
14
+ while (!stack .isEmpty () && nums [stack .peek ()] < nums [i ]) {
15
+ end = Math .max (end , stack .pop ());
16
+ }
17
+ stack .push (i );
18
+ }
19
+ return end - start > 0 ? end - start + 1 : 0 ;
20
+ }
33
21
}
You can’t perform that action at this time.
0 commit comments