268. Missing Number

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求:
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
这里写图片描述
也就是给n个数字,判断少了哪个数字。要求用线性的时间来进行探查,并利用有限的额外空间。
2,题目思路:
一开始想直接利用vector的排序函数对其排序,然后直接探查。但是貌似这样是违背题意的。顺带一说,给vector排序的办法:

#include<algorithm>
#include<vector>//两个头文件不能少

sort(nums.begin(),nums.end());

因此,在判断长串的数字是否相等时,又用到了异或(XOR)的办法,也即相同取0,不同取1(按位异或)。{1,2,3} ^ {1,2}的结果就是3。
Perfect for the compare the different number!
3,程序源码

#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;


class Solution {
public:
    int missingNumber(vector<int>& nums) {
        //sort(nums.begin(),nums.end());
        int count = nums.size();
        int res = count;
        for (int i = 0; i < count;i++)
        {
            res = res ^ nums[i];
            res = res ^ i;
        }
        return res;
    }
};

int main()
{
    Solution Sol;
    vector<int> valList = {0,1};
    cout<<Sol.missingNumber(valList)<<endl;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值