LeetCode-448-找到所有数组中消失的数字

找到所有数组中消失的数字

题目描述:给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:哈希法

首先,将1~n的数字初始化到hashSet里,然后判断原数组nums的元素如果在hashSset里面,则移除,最后剩下的就是在 [1, n] 范围内但没有出现在 nums 中的数字。

解法二:原地算法

首先,遍历原数组,将相应位置的元素对应的索引位置的值标记为负数,最后,再遍历一次数组,把非负数挑出来即为在 [1, n] 范围内但没有出现在 nums 中的数字

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class LeetCode_448 {
    /**
     * 哈希法
     *
     * @param nums 原数组
     * @return
     */
    public static List<Integer> findDisappearedNumbers(int[] nums) {
        Set<Integer> numbers = new HashSet<>();
        // 将1~n的数字初始化到hashSet里
        for (int i = 1; i <= nums.length; i++) {
            numbers.add(i);
        }
        // 判断原数组nums的元素如果在hashSset里面,则移除,最后剩下的就是在 [1, n] 范围内但没有出现在 nums 中的数字
        for (int num : nums) {
            if (numbers.contains(num)) {
                numbers.remove(num);
            }
        }
        return new ArrayList<>(numbers);
    }

    /**
     * 原地算法
     *
     * @param nums 原数组
     * @return
     */
    public static List<Integer> findDisappearedNumbers2(int[] nums) {
        // 遍历原数组,将相应位置的元素对应的索引位置的值标记为负数
        for (int i = 0; i < nums.length; i++) {
            int index = Math.abs(nums[i]);
            nums[index - 1] = Math.abs(nums[index - 1]) * -1;
        }
        // 最后,再遍历一次数组,把非负数挑出来即为在 [1, n] 范围内但没有出现在 nums 中的数字
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                result.add(i + 1);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {4, 3, 2, 7, 8, 2, 3, 1};
        // 测试用例,期望输出: 5,6
        System.out.println(findDisappearedNumbers(nums).stream().map(e -> String.valueOf(e)).collect(Collectors.joining(",")));
        System.out.println(findDisappearedNumbers2(nums).stream().map(e -> String.valueOf(e)).collect(Collectors.joining(",")));
    }
}

【每日寄语】 为人贵在“实”,工作贵在“专”,学习贵在“恒”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

醉舞经阁-半卷书

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

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

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

打赏作者

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

抵扣说明:

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

余额充值