1.问题描述
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1
Input: [3,0,1] Output: 2
Example 2
Input: [9,6,4,2,3,5,7,0,1] Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
2.算法分析
该问题没有描述清楚,如果数组为空该返回什么呢?如果大小为n的数组是连续的,那么该返回什么?根据程序此种情况应该是返回n.有以下两种方法实现
1)中规中矩的方法:
a) 先对数组进行排序;
b) 遍历元素,看元素值和数组下标是否一一对应相等;
c) 若相等,返回最大值的下一个;若不等,返回当前不等的值即可;
2)使用异或运算,转换为single number问题
a) 添加一个辅助元素 num = nums.size();
b) 如果值不缺失,只有num“出现”一次
c) 如果值缺失,缺失值只出现一次(即下标)
3.代码实现
class Solution {
public:
int missingNumber(vector<int>& nums) {
//解法1:先排序
/*
sort(nums.begin(), nums.end());
int i = 0;
for(i = 0; i < nums.size();i++){
if(nums[i] != i)
return i;
}
//数组是连续的,缺的是最后一个加1,而上面循环结束以后已经给i加1了
return i;
*/
//解法2:转换为Single Number问题
//如果有缺失值,那么对应的序号下标只出现一次,其他出现两次
//如果没有缺失值,那么只有nums.size()出现了一次
int res = nums.size();
for(int i = 0; i<nums.size();i++){
res ^= i;
res ^= nums[i];
}
return res;
}
};