Binary search --- ordered array of Single Element

Single Element ordered array of

540. Single Element in a Sorted Array (Medium)

Input: [1, 1, 2, 3, 3, 4, 4, 8, 8]
Output: 2

Subject description:

  An ordered array has only one number does not appear twice, to find this number.

Analysis of ideas:

  Solutions require the time complexity of the O (lgn), and therefore can not traverse the array to solve the XOR operation, the time complexity is done O (n).

  Makes index appear only as a number of index in the array, after the index, in pairs originally present status array is broken. If m is an even number, and m + 1 <index, then nums [m] == nums [m + 1] if m + 1> = index, then the nums [m]! = Nums [m + 1].

  Law is known from the above, if nums [m] == nums [m + 1], then the index is present in the [m + 2, h], if nums [m]! = Nums [m + 1], then the index is present in the [l, m]. Since assignment expression h is h = m, then it can only use the loop condition l <h This form.

Code

public int singleNonDuplicate(int []nums){
    int l=0;
    int h=nums.length-1;
    while(l<h){
        int m=l+(h-l)/2;
        if(m%2==1)
            m--;   //保证l/h/m都在偶数位
        if(nums[m]==nums[m+1]){
            l=m+2;
        }else{
            h=m;
        }
    }
    return nums[l];
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11106696.html