标签:逆序对 tps color div solution ret 最大值 problems art
https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
solution 1
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { vector<int> t = nums; sort(t.begin(), t.end()); int start = 0, end = nums.size() -1; while (start < nums.size() && t[start] == nums[start]) ++start; // cout << start << endl; while (end > start &&t[end] == nums[end]) --end; // cout << end << endl; return end - start + 1; } };
solution 2
class Solution { public: // max递增序列最大值,从头开始 // min递减序列最小值,从尾开始 // end 从前向后扩展,start从后向前扩展 // 理解为寻找逆序对的end和start位置 // 当前数若是小于递增序列的最大值,则存在逆序对 int findUnsortedSubarray(vector<int>& nums) { int n = nums.size(); int start = 0, end = -1; int max = nums[0], min = nums[n - 1]; for (int i = 0; i < n; ++i) { if (max > nums[i]) { end = i; } else { max = nums[i]; } if (min < nums[n - i - 1]) { start = n - i - 1; } else { min = nums[n - i -1]; } // cout << i <<" : " << end <<" " << start << endl; } // cout << end << " " << start << endl; return end - start + 1; } };
标签:逆序对 tps color div solution ret 最大值 problems art
原文地址:https://www.cnblogs.com/thunderdog/p/12895027.html