[leetcode] 268.Missing Number

题目:
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?
题意:
从0,1,2..n中抽出n个数,找出哪一个数没有被抽中。
思路:

  1. 最简单的方法是将这n个数加起来,再用原来的n+1个数的和即n*(n+1)/2,减去这n个数的和。
    但是这种题目,容易考的是当这些数累加起来会溢出。我采用的做法是使用long long保存中间结果,并且不是将所有的数累加起来再减去,我是一边添加那n个数,一边从0-n依次减去。比如原来数字是0,1,2,3,4,5,6;抽了一个数之后是1,2,3,4,5,6,那么我在对后面每一个数字往里面添加时(依次1,2,3,4,5,6)的同时,会减去前面每一个数字(依次减去0,1,2,3,4,5,6)。这两个加减是同时进行的。
    以上。
    代码如下:
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        long long result = 0;
        int i = 0;
        for(auto num:nums) {
            result += i;
            result -= num;
            i++;
        }
        result += i;
        return result;
    }
};

2.当然我们也可以采用位操作的方法,对于原始数组A,元素是0-n,对于抽取的数组B,元素是A中的元素少了一个。所以A,B两个数组合起来就是B中的元素都出现两次,另一个缺失的元素只出现一次。所以A,B中所有的元素异或起来的结果就是我们需要找的missing value。
以上。
代码如下:

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int result = 0;
        for(auto num:nums)
            result ^= num;
        int n = nums.size();
        for(int i = 0; i < nums.size() + 1; i++)
            result ^= i;
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值