题目如下:
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
给出一个整数数组nums,数组中每个元素的取值范围为[1,nums.length],有的元素会出现两次,有的出现一次。要求返回[1,nums.length]范围中未在数组中出现的数字。
解法分析: 在符合条件的数组(连续自然数)中,在数组元素按照从小到大顺序排列的情况下,数组中每项与其键的关系为:i+1=arr[i]。而这个数组是顺序无关的,故乱序条件下这个关系依然存在。故对数组进行两次遍历,第一次遍历通过每一项的值按照i+1=arr[i]的关系寻找到该值在排序状态下对应的键,并把该键对应的数组项置为负值。第二次遍历便可根据每一项是否为负值得出结果,若为非负值,说明该键值+1的值在原数组中未出现。
function findDisappearedNumbers(nums) {
var res = [],
length = nums.length;
for(var i = 0; i < length;i++){
var m = Math.abs(nums[i]) - 1; //这里须取绝对值,因为在之前的操作中这里可能已经被置为负值,这里判断需要按照原值进行。
nums[m] = nums[m] > 0 ? -nums[m] : nums[m];
}
for(var j = 0;j < length;j++){
if(nums[j] >= 0) res.push(j + 1);
}
return res;
};
之前一开始还想了个用字符串解决的办法,仅供大家一笑。。。。。。
function findDisappearedNumbers(nums) {
var length = nums.length,
numStr = ","+ nums.join(",")+",",
res = [];
for(var i = 1;i <= length;i++){
if(numStr.indexOf("," + i + ",") == -1)res.push(i);
}
return res;
};