|
1 | 1 | classSolution {
|
2 |
| -publicintfindUnsortedSubarray(int[]nums) { |
3 |
| - |
4 |
| -int[]copy =newint[nums.length]; |
5 |
| -for (inti=0;i<nums.length;i++) { |
6 |
| -copy[i] =nums[i]; |
7 |
| - } |
8 |
| - |
9 |
| -Arrays.sort(nums); |
10 |
| -intstart =0; |
11 |
| -intend =nums.length-1; |
12 |
| -intans =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 |
| -elseif (nums[start] ==copy[start] &&nums[end] !=copy[end]) { |
20 |
| -start++; |
21 |
| - } |
22 |
| -elseif (nums[start] !=copy[start] &&nums[end] ==copy[end]) { |
23 |
| -end--; |
24 |
| - } |
25 |
| -elseif (nums[start] ==copy[start] &&nums[end] ==copy[end]) { |
26 |
| -end--; |
27 |
| -start++; |
28 |
| - } |
29 |
| - } |
30 |
| - |
31 |
| -returnans; |
| 2 | +publicintfindUnsortedSubarray(int[]nums) { |
| 3 | +Stack<Integer>stack =newStack<>(); |
| 4 | +intstart =nums.length; |
| 5 | +for (inti =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 | +intend =0; |
| 13 | +for (inti =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 | +returnend -start >0 ?end -start +1 :0; |
| 20 | + } |
33 | 21 | }
|