-
Notifications
You must be signed in to change notification settings - Fork 0
/
581_Shortest Unsorted Continuous Subarray.cpp
64 lines (60 loc) · 1.35 KB
/
581_Shortest Unsorted Continuous Subarray.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
vector<int> temp(nums);
sort(temp.begin(), temp.end());
int p = 0, q = nums.size()-1;
while (nums[p] == temp[p]) p++;
while (nums[q] == temp[q]) q--;
if (p>=q) return 0;
else return q-p+1;
}
// method 2
int findUnsortedSubarray2(vector<int>& nums) {
int bound1 = 0, bound2 = 0, _max = nums[0];
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] < _max) {
if (bound1 == 0) bound1 = i;
bound2 = i;
} else {
_max = nums[i];
}
}
int inner_min = nums[bound1];
for (int i = bound1; i <= bound2; ++i) {
inner_min = min(inner_min, nums[i]);
}
for (int i = 0; i < bound1; ++i) {
if (nums[i] > inner_min) {
bound1 = min(bound1, i);
break;
}
}
if (bound1 >= bound2) return 0;
else return bound2-bound1+1;
}
};
int main() {
Solution s;
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
cout << s.findUnsortedSubarray2(nums);
return 0;
}
/**
7
2 6 4 8 10 9 15
5
5
1 3 5 4 2
4
5
2 5 3 1 4
5
*/