Java find missing numbers from ordered array

Title description

Choose n numbers from the n+1 numbers of 0,1,2,...,n to form an ordered array, find the missing number among these n numbers, and require O(n) to be as small as possible.

Example 1

enter

[0,1,2,3,4,5,7]

return value

6

 

import java.util.*;


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

 

Guess you like

Origin blog.csdn.net/luzhensmart/article/details/112851252