给定一个整数数组,你需要找到一个连续子数组,如果你只按升序对这个子数组进行排序,那么整个数组也将按升序排序。
你需要找到最短的这样的子数组并输出它的长度。
样例
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你需要对[6, 4, 8, 10, 9]按升序排列从而整个数组也变为升序。
注意事项
- 输入的数组长度范围为[1, 10,000]。
- 输入的数组可能会包含重复元素,本题升序的含义为<=。
class Solution {
public:
/**
* @param nums: an array
* @return: the shortest subarray's length
*/
int findUnsortedSubarray(vector<int> &nums) {
// Write your code here
int start = -1, end = -2;
vector<int> copy = nums;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] != copy[i])
{
if(start == -1)
{
start = i;
}
else
{
end= i;
}
}
}
return end-start+1;
}
};