题目以下:javascript
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.java
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.app
Example:this
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
给出一个整数数组nums,数组中每一个元素的取值范围为[1,nums.length],有的元素会出现两次,有的出现一次。要求返回[1,nums.length]范围中未在数组中出现的数字。spa
解法分析: 在符合条件的数组(连续天然数)中,在数组元素按照从小到大顺序排列的状况下,数组中每项与其键的关系为:i+1=arr[i]。而这个数组是顺序无关的,故乱序条件下这个关系依然存在。故对数组进行两次遍历,第一次遍历经过每一项的值按照i+1=arr[i]的关系寻找到该值在排序状态下对应的键,并把该键对应的数组项置为负值。第二次遍历即可根据每一项是否为负值得出结果,若为非负值,说明该键值+1的值在原数组中未出现。code
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; };