zoukankan      html  css  js  c++  java
  • 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();
        }
    }
    
    
  • 相关阅读:
    你没听过的乔布斯语录:苹果如果没这么独,可能更成功
    关于Apache mod_rewrite的中文配置、使用和语法介绍(实现URL重写和防盗链功能)
    与调试器共舞
    libxml2.dylb 导致<libxml/tree.h> 老是找不到头文件
    国家气象局提供的天气预报接口(完整Json接口)
    dSYM 文件分析工具
    总结
    1-22
    【图论】
    好像要开始图论了....但搜索还剩了点....
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12978597.html
Copyright © 2011-2022 走看看