581. Shortest Unsorted Continuous Subarray

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
找到一个连续的子数组,如果你只按升序对这个子数组进行排序,那么整个数组也将按照升序排序。

2,题目思路
对这样的一个需要排序的一个子数组,它的特性又是什么?
通过分析和观察,可以发现,在这样的子数组中,最小值大于子数组前面中的数组的最大值;
最大值小于后面数组中的数组的最小值。
因此,分别需要两个变量来记录这样的最大值和最小值,另外需要两个变量来记录满足条件的子数组的起始位置和结束位置。

3,程序源码

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size(), minVal = nums[n-1], maxVal = nums[0], start = -1, end = -2;
        for(int i = 1;i<n;i++)
        {
            maxVal = max(maxVal, nums[i]);
            minVal = min(minVal, nums[n-i-1]);

            if(nums[i] < maxVal)        end = i;
            if(nums[n-i-1] > minVal)    start = n-1-i;
        }

        return end - start + 1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值