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();
}
}
Lc448_找到所有數組中消失的數字
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.