题目来源【Leetcode】
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 <=.
直接放代码:
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
vector<int>temp(nums);
sort(nums.begin(), nums.end());
int judge = 0;
int count1 = 0;
int count2 = 0;
for(int i = 0; i < nums.size(); i++){
if(temp[i] != nums[i]){
count1 = i;
break;
}
else judge++;
}
for(int i = nums.size()-1 ; i >= 0; i -- ){
if(temp[i] != nums[i]){
count2 = nums.size()-i-1;
break;
}
}
if(count1 == 0 && count2 == 0 && judge == nums.size()) return 0;
else
return nums.size()-count1-count2;
}
};

本文介绍了一种算法,用于找到一个整数数组中需要排序的最短连续子数组,使得整个数组按升序排列。通过比较原始数组与排序后的数组来确定子数组的起始和结束位置。
422

被折叠的 条评论
为什么被折叠?



