您的位置:首页 > 移动开发

Find All Numbers Disappeared in an Array(哈希表)

2017-07-04 12:00 218 查看
题目描述

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.
思路
数值大小在1到n之间,乱序,1到N 可以很方便用数组值做索引值链到一个新数组上,但是without extra space,能否链到本数组上呢?可以把链到的索引对应的值加nums.length,然后找索引的时候模去nums.length,这样就不会因为加了这个值而影响索引,在最后可以用数组值和nums.length大小比较来判断对应索引是否存在。

List<Integer> res = new ArrayList();
for(int i = 0;i < nums.length;i++){
nums[(nums[i] - 1)%nums.length] += nums.length;
}
for(int i = 0;i < nums.length;i++){
if(nums[i] <= nums.length) res.add(i+1);
}
return res;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: