Skip to content

add 122 cpp version(4ms) #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 17, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
add 581 cpp version
  • Loading branch information
zouwx2cs committed Oct 17, 2018
commit 6e9162b899e3e6aab962a99d78cf358a237bbac8
40 changes: 40 additions & 0 deletions solution/581.Shortest Unsorted Continuous Subarray/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// i自左向右找到第一个逆序,
// j自右向左找到第一个逆序
// 找到nums[i, j]的上下界
// ij向外扩展找到满足上下界的最小[i, j]
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
if (1 == nums.size())
return 0 ;

int i = 0, j = nums.size()-1 ;
while (i < j && nums[i] <= nums[i+1])
++i ;
if (i >= j)
return 0 ;

while (nums[j-1] <= nums[j])
--j ;

//cout << i << ' ' << j << endl ;
int m = nums[i] ;
int M = m ;
for (int k = i; k <= j; ++k)
{
if (m > nums[k])
m = nums[k] ;
if (M < nums[k])
M = nums[k] ;
}
//cout << m << ' ' << M << endl ;

while (i >= 0 && m < nums[i])
--i ;
while (j < nums.size() && M > nums[j])
++j ;

//cout << i << ' ' << j << endl ;
return j-i-1 ;
}
};