Niuke.com, missing numbers

Title description (simple question)

Insert picture description here

solution

1. Regular search (linear)
Because the array is ordered, its subscript is its value.

public int solve(int[]a){
    
    
	if(a==null || a.length<1) return 0;
	for(int i=0;i<a.length;i++){
    
    
		if(a[i]!=i)
			return i;
	}
	return a.length;
}

Time complexity O(n);
Insert picture description here

2. Binary search

import java.util.*;


public class Solution {
    
    
    /**
     * 找缺失数字
     * @param a int整型一维数组 给定的数字串
     * @return int整型
     */
    public int solve (int[] a) {
    
    
        // write code here
        if(a==null || a.length<1) return 0;
       int left=0,right=a.length-1;
        
       while(left<=right){
    
    
           int mid = (left+right)/2;
           if(a[mid]==mid){
    
    
               //说明在前面
               left = mid+1;
           }else if(a[mid]>mid){
    
    //前面少了一个数
               right = mid-1;
           }//不会出现a[mid]<mid的情况,这样数据就不是有序的了。
       }
       return left;
    }
}

Insert picture description here

3. Use the characteristics of the question (using XOR)
because the subscript is the corresponding actual number, then together with the subscript, use XOR, use XOR one number twice to get the characteristic of 0, then which number is missing is the last Just got it.

import java.util.*;


public class Solution {
    
    
    /**
     * 找缺失数字
     * @param a int整型一维数组 给定的数字串
     * @return int整型
     */
    public int solve (int[] a) {
    
    
        // write code here
        if(a==null || a.length<1) return 0;
        int res= a.length ;//
         for(int i=0;i<a.length;i++){
    
    
             res ^=a[i]^i;
         
       }
       return res;
    }
}

Time complexity O(n)
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44861675/article/details/114934166