leetcode-581. 最短无序连续子数组
作者:互联网
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { // 笨方法,先排序,再从两端进行比较 int i = 0; int j = nums.size()-1; vector<int> res(nums.size(), 0); for(int i = 0; i < nums.size(); i++) res[i] = nums[i]; sort(res.begin(), res.end()); while(i<nums.size()&&res[i]==nums[i]) i++; while((j)>=0&&res[j]==nums[j]) j--; if(i>=j) return 0; return j-i+1; } };
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { // 从右到左:如果当前值的后面还有更小的值,不满足升序,当前值应该被排序 // 从左到右:如果当前值的前面还有更大的值,不满足升序,当前值应该被排序 int n = nums.size(); int mn = nums[n-1], l = n; for (int i = n - 1; i >= 0; --i) { if (nums[i] > mn) { l = i; cout<<"l: "<<l<<endl; } mn = min(nums[i], mn); } int mx = nums[0], r = 0; for (int i = 0; i < n; ++i) { if (nums[i] < mx) { r = i; cout<<"r: "<<r<<endl; } mx = max(nums[i], mx); } return max(r - l + 1, 0); } };
标签:nums,int,res,581,最短,vector,升序,leetcode,size 来源: https://www.cnblogs.com/ymec/p/15057555.html