Lc448_找到所有数组中消失的数字
package com.example.demo;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* 448. 找到所有数组中消失的数字
* 给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
* <p>
* 找到所有在 [1, n] 范围之间没有出现在数组中的数字。
* <p>
* 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
* <p>
* 示例:
* <p>
* 输入:
* [4,3,2,7,8,2,3,1]
* <p>
* 输出:
* [5,6]
*/
public class Lc448 {
/**
* 通过hash的key value 确定缺失的数字
* @param nums
* @return
*/
public static List<Integer> findDisappearedNumbers(int[] nums) {
// Hash table for keeping track of the numbers in the array
// Note that we can also use a set here since we are not
// really concerned with the frequency of numbers.
HashMap<Integer, Boolean> hashTable = new HashMap<Integer, Boolean>();
// Add each of the numbers to the hash table
for (int i = 0; i < nums.length; i++) {
hashTable.put(nums[i], true);
}
// Response array that would contain the missing numbers
List<Integer> result = new LinkedList<Integer>();
// Iterate over the numbers from 1 to N and add all those
// that don't appear in the hash table.
for (int i = 1; i <= nums.length; i++) {
if (!hashTable.containsKey(i)) {
result.add(i);
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {4, 3, 2, 7, 8, 2, 3, 1};
findDisappearedNumbers(nums).forEach(n -> {
System.out.println(n);
});
System.out.println();
}
}
不恋尘世浮华,不写红尘纷扰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理