LeetCode 268. Missing Number

268. 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.
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?

Solution

  • 题意即在一个n大小的数组中(包含0-n中n个数),找到那个缺少的数字。
  • 由于题目要求线性时间以及不能用额外的空间,于是我们利用位运算巧妙解决。
  • 注意到按位异或运算,倘若两个相同的数字按位异或那么得到0,倘若0和某个数按位异或那么还是该数。
  • 利用两个性质,我们可以将下标和数组的数字都异或一遍,那么最终成对的都会变成0(利用结合律和交换律思考),最终剩下的那个就是缺少的。代码如下
int missingNumber(int* nums, int numsSize) {
    int rnt = numsSize;
    for (int i = 0;i < numsSize;i++) {
        rnt ^= i;
        rnt ^= nums[i];
    }
    return rnt;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值