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大小比较来判断对应索引是否存在。
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;
相关文章推荐
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- 【Leetcode-easy-448】Find All Numbers Disappeared in an Array
- LeetCode--Find All Numbers Disappeared in an Array(找到数组中未出现的数字)
- LeetCode:Find All Numbers Disappeared in an Array
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- Leetcode_Array_Find All Numbers Disappeared in an Array
- [LeetCode] Find All Numbers Disappeared in an Array 找出数组中所有消失的数字
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- LeetCode [448. Find All Numbers Disappeared in an Array] 难度[easy]
- LeetCode - 448 - Find All Numbers Disappeared in an Array
- leetcode ---448---FindAllNumbersDisappearedinanArray
- LeetCode 448 Find All Numbers Disappeared in an Array
- [Leetcode,python] Find All Numbers Disappeared in an Array 寻找数组中消失的数字
- leetcode-448-Find All Numbers Disappeared in an Array
- leetcode(448). Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- LeetCode OJ|Array|Find All Numbers Disappeared in an Array
- [LeetCode] Find All Numbers Disappeared in an Array