ITPub博客

首页 > > > [LeetCode] Missing Number

[LeetCode] Missing Number

作者:Ruiyuan Li 时间:2015-08-24 00:00:00 0 删除 编辑

Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解题思路:

题意为找出0~n中缺少的那个数。要求O(n)的时间复杂度和O(1)的空间复杂度。

若采用排序查找的办法,则需要O(nlogn)的时间。

若采用hash的办法,则需要O(n)的空间复杂度。

采用位操作的办法。对数组中数的二进制位的1进行计数。然后对0~n中的二进制位的1进行计数。则两次计数的差则是missing number贡献的。

class Solution {
public:
    int missingNumber(vector& nums) {
        vector bitCount(sizeof(int) * 8, 0);           //n + 1个数中的bit计数
        vector missingBitCount(sizeof(int) * 8, 0);    //n个数中的bit计数
        
        int len = nums.size();
        for(int i=0; i> 1;
            }
        }
        
        for(int i = 0; i<=len; i++){
            int j = 0;
            int num = i;
            while(num){
                if(num & 1){
                    bitCount[j]++;
                }
                j++;
                num = num >> 1;
            }
        }
        
        int result = 0;
        for(int i = sizeof(int) * 8 - 1; i>=0; i--){
            result = result << 1;
            result += bitCount[i] - missingBitCount[i];
        }
        return result;
    }
};

利用异或的思想更加简单:

class Solution {
public:
    int missingNumber(vector& nums) {
        int num = 0;
        int len = nums.size();
        for(int i = 0; i


转载请注明: » [LeetCode] Missing Number
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825