LeetCode--581. 最短无序连续子数组

581. 最短无序连续子数组

思路:中间是无序数组,那么除去中间数组之外,左右两边必定是有序数组。
无序数组中最大的值,必定小于其右侧数组最小值
无序数组中最小的值,必定大于其左侧数组最大值

/**
 * 581. 最短无序连续子数组
 */

public class Solution581 {
    public int findUnsortedSubarray(int[] nums) {
        int length = nums.length;
        int maxn = Integer.MIN_VALUE, reight = -1;
        int minn = Integer.MAX_VALUE, left = -1;
        for (int i = 0; i < length; i++) {
            if (maxn > nums[i]) {
                // 从左到右找, 无序数组中最大的值 必定小于 在其右侧的值
                reight = i;
            } else {
                // 记录最大值
                maxn = nums[i];
            }
            if (minn < nums[length - i - 1]) {
                // 从左到右找, 无序数组中最小的值 必定大于 在其右侧的值
                left = length - i - 1;
            } else {
                // 记录最小值
                minn = nums[length - i - 1];
            }
        }
        return reight == left ? 0 : reight - left + 1;
    }

    public static void main(String[] args) {
        Solution581 solution581 = new Solution581();
        System.out.println(solution581.findUnsortedSubarray(new int[]{1,2,4,5,3}));
        System.out.println(solution581.findUnsortedSubarray(new int[]{2,3,3,2,4}));
        System.out.println(solution581.findUnsortedSubarray(new int[]{2,6,4,8,10,9,15}));
        System.out.println(solution581.findUnsortedSubarray(new int[]{1,2,3,4,5,6,7}));
        System.out.println(solution581.findUnsortedSubarray(new int[]{1,2}));
        System.out.println(solution581.findUnsortedSubarray(new int[]{2,1}));
        System.out.println(solution581.findUnsortedSubarray(new int[]{1,3,3,3,2}));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值