晨哥Leetcode 581. Shortest Unsorted Continuous Subarray

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.

算法一:
排序,然后跟原数组比对,有什么不一样
有几个注意点

  1. 数组要copy, 用Arrays.copyOf(int[] original,int newLength)
  2. 如果数组已经是完全排序的,要早点返回
public int findUnsortedSubarray(int[] nums) {
        int[] copy = Arrays.copyOf(nums, nums.length); 
        Arrays.sort(copy);
        int res = nums.length;
        int i = 0;
        while(i < nums.length && copy[i] == nums[i]) {
            res--; i++;
        }
        if(res == 0) return res;
        i = nums.length -1;
        while(i >= 0 && copy[i] == nums[i]) {
            res--; i--;
        }      
        return res;
    }

算法2 有点难懂
既然不符合排序规则,那么肯定能找到两边各自的一个突变的点
右边的end这个数, 比它左边的数中最大的要小,它是个突变
(正常来说,右边的数要比左边所有的数都大,比最大的数还大)
一边找,一边更新目前为止最大的值
从左边一直找过来,最后一个不正常的突变的数,就是end
反之从右边找过来,可以找到最后一个不正常的数,在最左边是begin

public int findUnsortedSubarray(int[] nums) {
        int max = nums[0];
        int end = -1, beg = -1;
        for(int i=1;i<nums.length;i++) {
            if(nums[i] < max) {
                end = i;
            }
             max = Math.max(max, nums[i]);
        }
        int min = nums[nums.length-1];
        for(int i=nums.length-2;i>=0;i--) {
            if(nums[i] > min) {
                beg = i;
            }
             min = Math.min(min, nums[i]);
        }
        return end == -1 ? 0 : end - beg +1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值