[leetcode] 581. Shortest Unsorted Continuous Subarray

网友投稿 570 2022-10-20

[leetcode] 581. Shortest Unsorted Continuous Subarray

[leetcode] 581. Shortest Unsorted Continuous Subarray

Description

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:

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

分析

题目的意思是:给定一个数组,找出一个连续子数组,如果这个子数组递增,那么整个数组就递增。

从前往后寻找最大值,如果遇见元素小于前面的最大值,我们找到右边界;从后往前寻找最小值,如果遇见的元素大于前面的最小值,我们找到左边界。

代码

class Solution {public: int findUnsortedSubarray(vector& nums) { int len=nums.size(); int min_value=nums[len-1]; int max_value=nums[0]; int r=-1; int l=0; for(int i=0;imin_value){ l=len-1-i; } } return r-l+1; }};

参考文献

​​581. Shortest Unsorted Continuous Subarray​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringCloud:feign对象传参和普通传参及遇到的坑解决
下一篇:VirtualAPK- 滴滴 Android 插件化框架
相关文章

 发表评论

暂时没有评论,来抢沙发吧~