Shortest Unsorted Continuous Subarray
Description
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.
Solution
/**
*
*/
package Easy;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @author:DaciVin
* @version:2019年12月16日
*/
public class LeetCode581 {
/**
* @param args
*/
public static int findUnsortedSubarray(int[] nums) {
int lens=nums.length;
int []numc= Arrays.copyOf(nums, lens);
Arrays.sort(numc);
int len=nums.length;
int l=0,r=nums.length;
// ArrayList list=new ArrayList<Integer>();
for(int i=0;i<len;i++) {
if(numc[i]!=nums[i]) { l=i;break;}
}
for(int j=len-1;j>0;j--) {
if(numc[j]!=nums[j]) {r=j;break;}
}
return r-l+1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[]nums=new int[]{1,3,2,5,4,7,6,8};
System.out.println(findUnsortedSubarray(nums));
}
}