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

来源:互联网 发布:mac怎么输入省略号 编辑:程序博客网 时间:2024/06/16 17:00

题目描述

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;


原创粉丝点击