您的位置:首页 > 其它

268. Missing Number

2018-03-05 19:28 162 查看
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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: