问题描述:
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 <=.
解题思路:
这道题是个easy,但是我做了30多分钟,感觉自己是不是练习的少了。。
这道题的各种情况比较多,如果不找全就会不能通过OJ
需要重排最明显的是:
相邻的两个数字顺序反了,就像给出的例子那样,但是如果之比较相邻的,长度会出错。
所以我们比较当前数字与之前的最大值:
1. 若当前数字小于最大值,则说明需要排序,从头遍历数组找到起始位置
2. 在与最大值比较后,首先检查start是否为-1:
a. 若为-1,则表明还没有出现要排序的情况
b. 若不为-1,则仍需检查当前值与numss[start]的值: 例: [1, 3, 5, 4, 2]
代码:
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { if(nums.size() == 0) return 0; int prevMax = nums[0]; int start = -1; int end = -1; for(int i = 1; i < nums.size(); i++){ if(nums[i] < prevMax){ if(start == -1 || nums[i] < nums[start]){ for(int j = 0; j < i; j++){ if(nums[j] > nums[i] ){ start = j; break; } } } end = i; }else if(nums[i] > prevMax){ prevMax = nums[i]; } } return start != -1 ? (end - start + 1) : 0; } };