581. Shortest Unsorted Continuous Subarray 最短未排序的子数组

本文介绍了一种高效算法,用于找出使整个数组有序所需的最短连续子数组长度。通过一次遍历并使用两个指针记录起始和结束位置,实现了O(n)的时间复杂度和O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.

题目解释:找出数组中没有正确排序的数组的个数

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        int max=nums[0];
        int begin=-1;
        int end=-2;
        int min=nums[n-1];
        for(int i=1;i<n;i++){
            max=Math.max(max,nums[i]);
            min=Math.min(min,nums[n-1-i]);
            if(max>nums[i])end=i;
            if(min<nums[n-1-i])begin=n-1-i;
        }
        return end-begin+1;
    }
}

用begin和end分别表示不符合排序要求的首位位置

【O(n)时间复杂度和O(1)空间复杂度】

分别把数组的第一个和最后一个当做最大和最小值

以第一个当做max值来讲,从下一位元素遍历到最后一位元素,取max和元素中的最大值最为更新的max,若max没有被更新,即max>nums[i],说明后一个元素比当前元素小,是不符合题目所说有小到大排序的的,于是把end确定在当前元素位置即i。继续向后遍历直到最后一位,这样可找到小数排在大数后面的情况

把最后一个当做min值得做法,同上

至于begin和end一个被定义成-1,一个被定义成-2,是因为比如说,序列是从小到大排列的,这时候end-begin+1=0,为了满足此公式,作如上定义

以上是我个人想法,可能有偏颇






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值