您的位置:首页 > 其它

Shortest Unsorted Continuous Subarray问题及解法

2017-05-15 13:53 148 查看
问题描述:

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.

示例:

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.

问题分析:
根据题意,我们可以先把数组升序排序,比较哪些元素变了,左右两边发生变化的元素的位置就是要求的子数组的长度范围。

过程详见代码:

class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
vector<int> nums2 = nums;
sort(nums.begin(),nums.end());
int begin = -1;
int end = -2;
for(int i = 0;i < nums.size(); i++)
{
if(nums[i] != nums2[i])
{
if(begin == -1)
begin = i;
end = i;
}
}
return end - begin + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: