力扣-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;
    }
}

 

posted @ 2020-10-29 12:13  Peterxiazhen  阅读(95)  评论(0编辑  收藏  举报