2.2.3 无序数组需要排序的最短子数组

2019-05-16  本文已影响0人  RockyLuo_290f

对于一个无序数组A,请设计一个算法,求出需要排序的最短子数组的长度。

给定一个整数数组A及它的大小n,请返回最短子数组的长度。

测试样例:
[1,5,3,4,2,6,7],7
返回:4

public class ShortSubsequence {
    public static int findShortest(int[] A, int n) {
        // write code here
        if(A == null || A.length < 2) return 0;
        
        int[] temp = new int[A.length];
        System.arraycopy(A,0,temp,0,A.length);
        Arrays.sort(temp);
        int left =0;
        int right =A.length -1;
        while( left < A.length && A[left] == temp[left]){
            left++;
        }
        while(right > left && A[right] == temp[right]){
            right--;
        }
        return right-left+1;
    }
    
    public static void main(String[] args) {
        int[] ans = {1,2,3,3,8,9};
        System.out.println(findShortest(ans,6));
    }
}

上一篇 下一篇

猜你喜欢

热点阅读