[LintCode] Find the Missing Number 寻找丢失的数字

本文介绍了一种算法问题——寻找长度为N且包含0到N之间的整数的数组中缺失的数字。提供了两种解决方案:一种使用求和的方法找到缺失的数字,另一种采用位操作的方式解决。这些方法都在LeetCode上进行了验证。

Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array.

Example

Given N = 3 and the array [0, 1, 3], return 2.

Challenge

Do it in-place with O(1) extra memory and O(n) time.

这道题是LeetCode上的原题,请参见我之前的博客Missing Number 丢失的数字。那道题用了两种方法解题,但是LintCode的OJ更加严格,有一个超大的数据集,求和会超过int的范围,所以对于解法一的话需要用long来计算数组之和,其余部分都一样,记得最后把结果转成int即可,参见代码如下:

解法一:

class Solution {
public:
    /**    
     * @param nums: a vector of integers
     * @return: an integer
     */
    int findMissing(vector<int> &nums) {
        // write your code here
        long sum = 0, n = nums.size();
        for (auto &a : nums) {
            sum += a;
        }
        return (int)(n * (n + 1) * 0.5 - sum);
    }
};

用位操作Bit Manipulation和之前没有区别,参见代码如下:

解法二:

class Solution {
public:
    /**    
     * @param nums: a vector of integers
     * @return: an integer
     */
    int findMissing(vector<int> &nums) {
        // write your code here
        int res = 0;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); ++i) {
            res ^= nums[i] ^ (i + 1);
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:寻找丢失的数字[LintCode] Find the Missing Number ,如需转载请自行联系原博主。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值