【Java】【JS】LeetCode - 哈希表 - 原地标记 - #448 数组中的消失数字

日子总会一天天好起来。力扣力扣:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/

给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

输入: [4,3,2,7,8,2,3,1]

输出: [5,6]

方法一: 使用哈希表

我们用一个哈希表 hash 来记录我们在数组中遇到的数字。我们也可以用集合 set 来记录,因为我们并不关心数字出现的次数。
然后遍历给定数组的元素,插入到哈希表中,即使哈希表中已经存在某元素,再次插入了也会覆盖
现在我们知道了数组中存在那些数字,只需从 1⋯N 范围中找到缺失的数字。
从 1⋯N 检查哈希表中是否存在,若不存在则添加到存放答案的数组中。

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        HashMap<Integer, Boolean> hashtable = new HashMap<Integer, Boolean>();
        for(int i = 0; i < nums.length; i++){
            hashtable.put(nums[i],true);
        }
        List<Integer> result = new LinkedList<Integer>();
        for(int i = 1; i <= nums.length; i++){
            if(!hashtable.containsKey(i)){
                result.add(i);
            }
        }
        return result;
    }
}
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
    const length = nums.length;
    const map = {};
    nums.forEach(num => (map[num] = true));
    const result = [];
    for(let i = 1; i <= length; i++){
        if(!map[i]){
            result.push(i);
        }
    }
    return result;
};
  • 时间复杂度:O(N)。空间复杂度:O(N)。

方法二: 原地标记 

遍历输入数组的每个元素一次。
我们将把 |nums[i]|-1 索引位置的元素标记为负数。即 nums[|nums[i] |- 1] ×−1 。
然后遍历数组,若当前数组元素 nums[i] 为负数,说明我们在数组中存在数字 i+1。

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        for(int i = 0; i < nums.length; i++){
            int newIndex = Math.abs(nums[i])-1;
            if(nums[newIndex] > 0){
                nums[newIndex] *= -1;
            }
        }
        List<Integer> result = new LinkedList<Integer>();
        for(int i = 0; i < nums.length; i++){
            if(nums[i] > 0){
                result.add(i+1); 
            }
        }
        return result;
    }
}
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
    const length = nums.length;
    nums.forEach(num => {
        const absNum = Math.abs(num);
        if(nums[absNum-1] > 0){
            nums[absNum-1] *= -1;
        }
    });
    const result = [];
    for(let i = 1; i <= length; i++){
        if(nums[i-1] > 0){
            result.push(i);
        }
    }
    return result;
};

时间复杂度:O(N) 无需额外空间

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白Rachel

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值