problem

​581. Shortest Unsorted Continuous Subarray​

题意:感觉题意理解的不是非常明白。

solution1:

使用一个辅助数组,新建一个跟原数组一模一样的数组,然后排序。从数组起始位置开始,两个数组相互比较,当对应位置数字不同的时候停止,同理再从末尾开始,对应位置上比较,也是遇到不同的数字时停止,这样中间一段就是最短无序连续子数组。

class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size();
int i = 0, j = n-1;//err.
vector<int> tmp = nums;
sort(tmp.begin(), tmp.end());
while(i<n && tmp[i]==nums[i]) i++;
while(j>i && tmp[j]==nums[j]) j--;//err.
return j-i+1;

}
};

 

 

参考

1. ​​Leetcode_easy_581. Shortest Unsorted Continuous Subarray​​;

2. ​​Grandyang​​;

3. ​​C++ O(n) solution​​;

4. ​​c++ O(n) one-pass solution which beats almost​​;