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
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; }