581. Shortest Unsorted Continuous Subarray

网友投稿 522 2022-11-11

581. Shortest Unsorted Continuous Subarray

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.

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(int[] nums) { int n = nums.length; int beg = -1; int end = -2; // end is -2 is because it works if the array is already in ascending order int min = nums[n-1]; // from right to left int max = nums[0]; // from left to right for(int i=0; i min) beg = n-1-i; } return end - beg + 1; // if array is already in ascending order, -2 - (-1) + 1 = 0

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

上一篇:605. Can Place Flowers
下一篇:解决maven maven.compiler.source和maven.compiler.target的坑
相关文章

 发表评论

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