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.
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
普通算法 耗时不通过
var findDisappearedNumbers = function(nums) {
var result = [];
var len = nums.length;
for(var i = 1; i <= len; i++) {
if(nums.indexOf(i) === -1) result.push(i);
}
return result;
};
修改后
var findDisappearedNumbers = function(nums) {
var result = [];
// 修改原数组
for(var i = 0; i <= nums.length; i++) {
var val = Math.abs(nums[i]) -1;
if(nums[val] > 0) nums[val] = -nums[val];
}
// 查找元素
for(var j = 0; j < nums.length; j++) {
if(nums[j] > 0) {
result.push(j+1);
}
}
return result;
};