-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_581_ShortestUnsortedContinuousSubArray.cpp
90 lines (71 loc) · 2.07 KB
/
LC_581_ShortestUnsortedContinuousSubArray.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
581. Shortest Unsorted Continuous Subarray
*/
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size();
int l = 0, r=-1;
int mn = nums.back(), mx=nums.front();
for(int i=0; i<n; i++)
{
mx = max(nums[i], mx);
mn = min(nums[n-1-i], mn);
if(mx > nums[i])
r = i;
if(mn < nums[n-1-i])
l = n-1-i;
}
return r-l+1;
}//end
int findUnsortedSubarray_2(vector<int>& nums) {
int n = nums.size();
int l = 0, r=n-1;
int mn = INT_MAX, mx=INT_MIN;
while(l<n-1 and nums[l] <= nums[l+1])
l++;
if(l == n-1) // already sorted in aescending order
return 0;
while(r>0 and nums[r-1]<=nums[r])
r--;
if(r==0) // sorted in descending order
return n;
for(int i=l; i<=r; i++)
{
mx = max(nums[i], mx);
mn = min(nums[i], mn);
}
while(l>0 and nums[l-1] > mn)
l--;
while(r<n-1 and mx > nums[r+1])
r++;
return r-l+1;
}//end
int findUnsortedSubarray_1(vector<int>& nums) {
int n = nums.size();
int l = -1, r=-1;
vector<int> sorted(nums);
sort(sorted.begin(), sorted.end());
for(int i=0; i<n; i++)
{
if(l == -1 and nums[i] != sorted[i])
{
l = i;
r = i;
}
else if(l != -1 and nums[i] != sorted[i])
{
r = i;
}
}
// for(int x: nums)
// cout<<x<<" ";
// cout<<endl;
// for(int x: sorted)
// cout<<x<<" ";
// cout<<endl;
// cout<<l<<" "<<r<<endl;
return l == -1 ? 0 : r-l+1;
}//end
};