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数组中的每一项有元素和下标两个属性,充分利用好这两个属性,就可以轻松做出本题。
思路简析:遍历nums数组,将其中已经存在的数对应的下标序列取出,将nums[下标序列] 的数标记为负。之后再遍历一遍nums数组,只要是非负的数,就把此下标取出,存入结果数组result。最后返回result。
具体的java代码如下:
public class Solution {
public List findDisappearedNumbers(int[] nums) {
List result = new ArrayList();
if (nums == null || nums.length == 0)
return result;
for (int i=0; i 0)
nums[index] = -nums[index];
}
for (int i=0; i 0)
result.add(i+1);
}
return result;
}
}