<LeetCode OJ> 268. Missing Number

268. Missing Number

Total Accepted: 31740  Total Submissions: 83547  Difficulty: Medium

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?





分析:DONE

我真蛋疼,题意理解错了,我还以为是干嘛呢!
后来才明白原来是随机从0到size()选取了n个数,其中只有一个丢失了(显然的)。
别人的算法:数学推出,0到size()的总和减去当前数组和sum

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int sum = 0;  
        for(int num: nums)
            sum += num;  
        int n = nums.size();  
        return (n * (n + 1))/ 2 - sum;  
    }
};


这道问题被标注为位运算问题:参考讨论区的位运算解法:

这个异或运算以前用到过,到这道题还是想不起这个方法,我真是日了狗了!

异或运算xor,
0 ^ a = a ^ 0 =a
a ^ b = b ^ a
a ^ a = 0
0到size()间的所有数一起与数组中的数进行异或运算,
因为同则0,0异或某个未出现的数将存活下来

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int res = 0;
        for (int i = 1; i <= nums.size(); i++) 
            res =res ^ i ^ nums[i-1]; 
        return res; 
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50457902

原作者博客:http://blog.csdn.net/ebowtang


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值