Missing Number(讲解一个非常好的方法)

题目名称
Missing Number—LeetCode链接

描述
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?

分析
  考虑到将原数组排序后,如果不缺失元素,数组下标值和元素值是相等的,所以常规思路就是将数组排序,然后根据位置查找,如果丢失的是最后一个数字,则返回最后一个数字;否则从数组头部开始遍历,直到找到值与下标不相符的,返回下标数字。

C++代码

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int size = nums.size();
        if(nums[size-1]==size-1)
            return size;
        for(int i=0;i<size;i++){
            if(nums[i]!=i)
                return i;
        }
    }
};

总结
  这里给出一个非常棒的答案,不需要将原数组排序,而采用异或操作符^。先给出代码,再做解释:

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

The operation of xor is commutative and associative. That is A ^ B = B^A and (A ^ B) ^ C = A ^ (B ^ C). Therefore, A^C^B^A^C = A^A^C^C^B = B. So for this code, the order of the numbers does not matter at all.
  上段内容是这个代码的作者的解释,很好懂,举个例子,给定一个数组:

4,2,0,1

  result初始值为0,做异或操作就是:0^(4^1)^(2^2)^(0^3)^(1^4)=3.
  答案看上去很巧妙,其实思路很简单,给定的数组肯定缺失一个数字,那么我对数组所有元素(4,2,0,1)和不缺失的情况(0,1,2,3,4)中所有元素进行异或连接操作,肯定能得到缺失的那个数字。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值