方法1: 新增布尔类型数组,标识存在的整数

    public static void findUnusedMiniNumber( ) {
        int[] arr = {18,4,8,9,16,1,14,7,19,3,0,5,2,11,6};

        boolean[] status = new boolean[arr.length];

        for ( int i=0;i<arr.length;i++) {
            if (arr[i] < arr.length){
                status[arr[i]]=true;
            }
        }
        for ( int i=0;i<status.length;i++ ) {
            if (status[i] == false) {
                System.out.println(i);
                break;
            }
        }
    }

方法2:while连续比较

    public static int missNum(){
        int[] arr = {18,4,8,9,16,1,14,7,19,3,0,5,2,11,6};
        int l = 0;
        int r = arr.length;
        while (l< r){
            if(arr[l] == l+1){
                l++;
            } else if(arr[l] <= l || arr[l] > r || arr[arr[l] -1] == arr[l]){
                arr[l] = arr[--r];
            } else {
                swap(arr, l, arr[l] - 1);
            }
        }
        return l+1;
    }

    public static void swap(int[] arr, int index1, int index2){
        int tmp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = tmp;
    }

 

 posted on 2019-04-09 20:32  ChaseForFuture  阅读(374)  评论(0编辑  收藏  举报