您的位置:首页 > 移动开发

Missing Number -- leetcode

2015-10-03 19:46 351 查看
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?

算法一,异或

思路同问题Single Number:所有的数出现2次,只有一个数出现次。找出那个数。

1.对给出的数做一遍XOR。

2.对着期望的数全体做一遍XOR。

这样,所有的数都做了2次XOR,只有那个缺失的数只做了一次XOR。

class Solution {
public:
int missingNumber(vector<int>& nums) {
int ans = 0, i = 0;
for (auto n: nums)
ans ^= n ^ ++i;
return ans;
}
};

算法二,SUM

1.将给出的数,做一个累加和

2. 将期望的数,做一个累加和,

3,两者取差值。

此算法,不足之处,整数溢出问题。

class Solution {
public:
int missingNumber(vector<int>& nums) {
int i = 0, sum = 0;
for (auto n: nums) {
sum += ++i - n;
}
return sum;
}
};

算法三,交换

通过交换进行排序操作。

通过下标映射,将数直接交换到最终位置。

比如0, 移动到 nums[0];   3 移动到 nums[3]

最后,看一下,与下标不一致的数组元素。其下标即为所求。

在交换过程时,当碰到元素值为nums.size(),我们知道无法将其交换到最终位置。故作一个标志,指示此不一致位置。

并暂时略过此位置的交换。这个位置的理想值,将在后面会交换过来。而那时,nums.size()这个值,将会挪到新位置。并随之更新标记到新位置。

leetcode上实际执行时间为40ms。

class Solution {
public:
int missingNumber(vector<int>& nums) {
int missing = nums.size();
for (int i=0; i<nums.size(); i++) {
while (nums[i] != i) {
if (nums[i] != nums.size())
swap(nums[i], nums[nums[i]]);
else {
missing = i;
break;
}
}
}
return missing;
}
};

我将此写法也贴在了leetcode上

https://leetcode.com/discuss/56174/3-different-ideas-xor-sum-binary-search-java-code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息