File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
shortest-unsorted-continuous-subarray Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int findUnsortedSubarray (int [] nums ) {
3+
4+ int low =0 ,high =nums .length -1 ;
5+
6+ //find the first unsorted element from beginning
7+ while (low <nums .length -1 &&nums [low ]<=nums [low +1 ])
8+ low ++;
9+
10+ if (low ==nums .length -1 )
11+ return 0 ;
12+
13+
14+ //find the first unsorted element from end of the array
15+ while (high >0 &&nums [high ]>=nums [high -1 ])
16+ high --;
17+
18+ int minEl =Integer .MAX_VALUE ;
19+ int maxEl =Integer .MIN_VALUE ;
20+ for (int i =low ;i <=high ;i ++)
21+ {
22+ minEl =Math .min (minEl ,nums [i ]);
23+ maxEl =Math .max (maxEl ,nums [i ]);
24+ }
25+
26+ //extend subarray if we encounter a element less than minimum to include
27+ while (low >0 &&nums [low -1 ]>minEl )
28+ low --;
29+
30+
31+ //extend subarray if we encounter a element greater than max of the subarray to include it
32+
33+ while (high <nums .length -1 &&nums [high +1 ]<maxEl )
34+ high ++;
35+
36+
37+ return high -low +1 ;
38+
39+
40+ }
41+ }
You can’t perform that action at this time.
0 commit comments