File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int findUnsortedSubarray (vector<int >& nums) {
4
+ int n = nums.size ();
5
+ // 1. find the first i where nums[i] < nums[j] && i > j; start = j
6
+ // 2. find the last i where nums[i] > nums[j] && i < j; end = j
7
+ // ans = end - start + 1;
8
+
9
+ // start and end are set this way so that by default, ans = end - start + 1 = 0
10
+ int start = 0 , end = -1 ;
11
+
12
+ // 1. find the first i where nums[i] < nums[j] && i > j; start = j
13
+ int min_ = INT_MAX;
14
+ for (int i = 0 ; i < n; i++)
15
+ if (nums[n-i-1 ] <= min_) min_ = nums[n-i-1 ];
16
+ else start = n-i-1 ;
17
+
18
+ // 2. find the last i where nums[i] > nums[j] && i < j; end = j
19
+ int max_ = INT_MIN;
20
+ for (int i = 0 ; i < n; i++)
21
+ if (nums[i] >= max_) max_ = nums[i];
22
+ else end = i;
23
+
24
+ return end - start + 1 ;
25
+ }
26
+ };
You can’t perform that action at this time.
0 commit comments