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: 只须要排序[6,4,8,10,9]就能够保证整个数组的有序this

思路

  • 大致思路是这样的:若是当前元素比它前面的元素中的最大的值小,那它就在待排序的子数组里;若是当前元素比它后面元素中的最小值要大,那它也须要包含在待排序的子数组里。
  • 咱们用一个变量(max)来保存遍历过的元素中的最大值,用一个变量(min)来保存从数组尾部遍历的元素中的最小值。
  • 而后咱们只要经过遍历找到,最后一位待排序元素和最前面的待排序元素就能够了。

解法

public int findUnsortedSubarray(int[] nums) {
        int length = nums.length;
        int start =-1 ;
        int end = -2;
        int min = nums[length-1];
        int max = nums[0];
        
        for(int i=1;i<length;i++){
            max = Math.max(max, nums[i]);
            min = Math.min(min, nums[length-i-1]);
            
            if(nums[i] < max){
                end = i;
            }
            if(nums[length-1-i] > min){
                start = length-1-i;
            }
        }
        return end-start+1;
    }
相关文章
相关标签/搜索