目录结构
1.题目
给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是最短的,请输出它的长度。
示例:
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
说明 :
- 输入的数组长度范围在 [1, 10,000]。
- 输入的数组可能包含重复元素 ,所以升序的意思是<=。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
基本思路:
- 正序找到开始出现乱序的位置(若已经遍历完整个数组,则证明数组本身有序,返回0即可);
- 逆序找到开始出现乱序的位置;
- 在乱序子数组里找到最大值和最小值;
- 以最大值和最小值定位整个数组出现乱序的子数组区间。
public class Solution581 {
@Test
public void test581() {
int[] nums = {2,1};
System.out.println(findUnsortedSubarray(nums));
}
public int findUnsortedSubarray(int[] nums) {
int i,j,len = nums.length;
for (i = 0;i<len-1;i++){
if (nums[i]>nums[i+1]){
break;
}
}
if (i == len -1){
return 0;
}
for (j = len-1;j>=0;j--){
if (nums[j-1]> nums[j]){
break;
}
}
int min = nums[i],max = nums[j];
for (int k = i;k<=j;k++){
max = Math.max(max,nums[k]);
min = Math.min(min,nums[k]);
}
int l,r;
for (l=i ;l>=0;l--){
if (nums[l]<=min){
break;
}
}
for (r = j;r<len;r++){
if (nums[r]>=max){
break;
}
}
return r-l-1;
}
}
- 时间复杂度:
- 空间复杂度: