一、题目
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
找出缺失的数。
二、思路
这道题解题方法较多,这里给出三种思路
1、异或运算 把数组中的每一个数,与1到n进行按位异或,最后剩下的,就是丢失的数。
2、求和法 求出1到n的累加和,和数组中给的数相减,差即为缺失的数
3、二分法 首先把数组排序,设中间元素为nums[mid],如果nums[mid]的值大于其下标,说明丢失的数字在左边,反之则在右边。时间复杂度O(nlogn),比前面两个方法慢,但是如果题目给的数组是事先排好序的,那么复杂度就是O(log n),所以这个方法还是很有意义的。
三、代码
class Solution {
public:
///方法1,异或运算
int missingNumber(vector<int>& nums) {
int result = 0;
for(int i=0; i<nums.size(); i++) {
result ^= (i+1)^nums[i];
}
return result;
}
///方法2,求和
int missingNumber2(vector<int>& nums) {
int result = 0;
for(int i=0; i<nums.size(); i++)
result += nums[i];
int n = nums.size();
int sum = n*(n+1)/2;
return sum - result;
}
///方法3,二分法
int missingNumber3(vector<int>& nums) {
sort(nums.begin(), nums.end());
int begin = 0, end = nums.size();
while(begin != end) {
int mid = begin+(end-begin)/2;
if(mid < nums[mid])
end = mid;
else
begin = mid+1;
}
return end;
}
};