[Offer] [53-2] [missing numbers 0 ~ n-1]

Title Description

All numbers in ascending order of length n-1 in the array are unique, and each number in the range of 0 ~ n-1. 0 ~ n 1-n numbers within the range, and there is only one number is not in the array, find this number.

[Cow brush off questions address network] No

Ideas analysis

  1. May utilize mathematical formulas, a formula arithmetic sequence, and to determine s1 0 ~ n-1, and then through the entire array, the value obtained by adding their s2, then the required values ​​s1-s2;
  2. Because it is incremented array, and the subscript 0 corresponding element is 0, the subscript n corresponding element is n, because of which lack an element, resulting in the subscript behind and corresponding elements are not equal, the problem is transformed into, Find First and a subscript of the element values ​​are not equal, binary search method may be utilized, and the index value determination intermediate element:
    • If equal, then the right half of a comparator;
    • If not equal, and the value of the element preceding it and its corresponding index are equal, then, is to find the value of the element, if the value of the element preceding it and its corresponding index are not equal, then, to find the left part.

Test Case

  1. Functional test: lack of digital array located at the beginning, middle, or end.
  2. Boundary value testing: 0 array, only one number.
  3. Special input test: an array of pointers is represented nullptr pointer.

Java code

public class Offer053_02 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

    public static int GetMissingNumber(int[] array) {
        return Solution1(array);
    }

    

    private static int Solution1(int[] array) {
        if(array==null || array.length<=0) {
            return -1;
        }
        int start = 0;
        int end = array.length-1;
        
        while(start< end) {
            int mid = (start+end)>>1;
            if(array[mid]!=mid) {
                
                if(mid == 0 || array[mid-1]==mid-1) {
                    return mid;
                }
                
                end = mid-1;
                
            }else {
                start = mid+1;
            }
        }
        
        return -1;
    }

    private static void test1() {
        int[] arr = {0,1,2,3,4,5,6,7,9,10,11};
        System.out.println(GetMissingNumber(arr));
    }

    private static void test2() {
        int[] arr = {1,2,3,4,5,6,7,8,9,10,11};
        System.out.println(GetMissingNumber(arr));
    }
    private static void test3() {
        int[] arr = {0};
        System.out.println(GetMissingNumber(arr));
    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer532-0n1zhong-que-shi-de-shu-zi.html