本文主要是介绍Find All Numbers Disappeared in an Array(哈希表),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
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;
这篇关于Find All Numbers Disappeared in an Array(哈希表)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!