题目描述
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
思路:
- 对数组排序,比对原数组和排序后数组,相同位置数字不同的两端。
- 从前往后维护一个最大值,如果当前值<最大值,记录end位置。从后往前维护最小值,如果当前值>最小值,记录start位置。
主要是第二个思路。
代码
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
map<int, int> index;
for (int i=0; i<nums.size(); ++i) {
index[i] = nums[i];
}
sort(nums.begin(), nums.end());
int l = 0, r = nums.size()-1;
for (int i=0; i<nums.size(); ++i) {
if (index[i] == nums[i]) l++;
else break;
}
if (l == nums.size()) return 0;
for (int i=nums.size()-1; i>=0; --i) {
if (index[i] == nums[i]) --r;
else break;
}
if (r == -1) return 0;
return r - l + 1;
}
};
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n = nums.size();
int min_ = nums[n-1];
int max_ = nums[0];
int st = -1, ed = -2;
for (int i=1; i<n; ++i) {
if (nums[i] < max_) ed = i;
if (nums[n-1-i] > min_) st = n-1-i;
min_ = min(nums[n-1-i], min_);
max_ = max(nums[i], max_);
}
return ed - st + 1;
}
};