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