力扣-448-找到所有数组中小时的数字
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
输入: [4,3,2,7,8,2,3,1] 输出: [5,6]
方法1:用HashMap存储1...N中的数字是否出现过
Map<Integer, Boolean> hashmap = new HashMap<Integer, Boolean>();
class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> res = new ArrayList<Integer>(); Map<Integer, Boolean> hashmap = new HashMap<Integer, Boolean>(); /*建立Hash映射*/ for(int i = 0; i < nums.length; i++) { hashmap.put(nums[i], true); } /*遍历hashmap,将未出现的数字加入到res散列表中*/ for(int index = 1; index <= nums.length; index++) { if(!hashmap.containsKey(index)) { res.add(index); } } return res; } }
方法二:原位计算,不增加额外的空间
我们可以不增加额外的空间,在输入数组本身用某种方法进行标记,最后面里找到缺失的数字。
我们将|nums[i]-1(后面有乘以-1,所以加绝对值,这样能正确找到索引位置)索引处的元素乘以-1,变为负数;如果1..N中的数没有出现,那么以其为索引处的元素就为正数。
最后我们遍历一遍,找到正数元素对应的下标即可。
class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> res = new ArrayList<Integer>(); for(int i = 0; i < nums.length; i++) { int newIndex = Math.abs(nums[i]) -1; if(nums[newIndex] > 0) { nums[newIndex] *= -1; } } for(int i = 1; i <= nums.length; i++) { if(nums[i - 1] > 0) { res.add(i); } } return res; } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!