[leetcode]268. Missing Number

本文介绍了一种高效算法,用于找出由0到n的整数数组中缺失的一个数字。通过两种方法实现:一种是排序后逐个比较数组下标与数值;另一种是使用异或操作,巧妙地避免了排序步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://leetcode.com/problems/missing-number/description/

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

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

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

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)中所有元素进行异或连接操作,肯定能得到缺失的那个数字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值