【一次过】Lintcode 196. 寻找缺失的数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/86559872

给出一个包含 0 .. N 中 N 个数的序列,找出0 .. N 中没有出现在序列中的那个数。

样例

N = 4 且序列为 [0, 1, 3] 时,缺失的数为2

挑战

在数组上原地完成,使用O(1)的额外空间和O(N)的时间。


解题思路1:

时间复杂度O(n),空间复杂度O(n)。利用空间换时间。类似Lintcode 189. 丢失的第一个正整数

public class Solution {
    /**
     * @param nums: An array of integers
     * @return: An integer
     */
    public int findMissing(int[] nums) {
        // write your code here
        int[] temp = new int[nums.length+1];
        for(int i=0; i<nums.length; i++)
            temp[nums[i]] = 1;
        
        for(int i=0; i<temp.length; i++)
            if(temp[i] == 0)
                return i;
        
        return 1;
    }
}

解题思路2:

时间复杂度O(n),空间复杂度O(1)。如果不缺失这个数可看出数组是一个以方差为1的等差数列,所以可以先求出这个完整数列的和。然后将目前的数组和求出,两者相减,则是缺失的数。

public class Solution {
    /**
     * @param nums: An array of integers
     * @return: An integer
     */
    public int findMissing(int[] nums) {
        // write your code here
        int n = nums.length;
        
        int realSum = n*(1+n)>>1;//等差数列求和公式:n*(a1 + an)/2
        
        int sum = 0;
        for(int i=0; i<nums.length; i++)
            sum += nums[i];
        
        return realSum - sum;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/86559872