您的位置:首页 > 编程语言 > C语言/C++

268. Missing Number

2016-07-20 10:29 411 查看

题目:Missing Number

原题链接:https://leetcode.com/problems/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?

给出一个数组含有n个唯一的元素从0,1,2。。。,n,找出丢失的那一个元素,例如数组元素为0,1,3则丢失的元素为3,要求算法必须要是线性时间复杂度,并尽量使用常数级额外的空间。

线性额外空间的算法:

开一个哈希数组,然后统计数组里面的所有元素,最后扫描一遍数组,找出缺少的那一个,代码如下:

class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
int hash[len + 1] = {};
for(int i = 0; i < len; ++i) {
hash[nums[i]] = 1;
}
for(int i = 0; i < len+1; ++i) {
if(!hash[i]) return i;
}
return -1;
}
};


常数空间复杂度算法:

利用位操作,以及“消除”的思想,定义ans = 0,然后去和数组里面每一个元素异或,然后在和从0到n的数字都分别异或一下,这样最终的结果就是丢失的那一个元素。代码如下:

class Solution {
public:
int missingNumber(vector<int>& nums) {
int ans = 0, i = 0;
for(auto num : nums) {
ans ^= num;
ans ^= i++;
}
return ans ^ i; //注意不要忘记和n异或一下
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C++