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;
    }
相關文章
相關標籤/搜索