• 當前位置:首頁 > IT技術 > 編程語言 > 正文

    448. 找到所有數組中消失的數字
    2021-11-30 22:45:10

    描述

    給你一個含 n 個整數的數組 nums ,其中 nums[i] 在區間 [1, n] 內。請你找出所有在 [1, n] 范圍內但沒有出現在 nums 中的數字,并以數組的形式返回結果。

    鏈接

    448. 找到所有數組中消失的數字 - 力扣(LeetCode) (leetcode-cn.com)

    ?

    解法:特殊標記(使得空間復雜度為 O(1))

    如何利用 nums 作為輔助數組,來記錄每個數字是否出現呢?
    對于第 i 個數字 nums[i],我們位置 (nums[i] - 1) % n 的位置增加 n,這樣不會覆蓋原數組,因為 (nums[i] - 1) % n = (nums[i] - 1 + n) % n,這樣如果最后遍歷完數組,nums[i] 小于等于 n,就是數組中中消失的數字。
    下圖以示例數據為例,演示了方法二的思路。

    ?

     1 class Solution {
     2     public List<Integer> findDisappearedNumbers(int[] nums) {
     3         int n = nums.length;
     4         for (int num : nums) {
     5             int x = (num - 1) % n; // 對應的 序號
     6             nums[x] += n;  // 把 有序號的 相加了 一遍
     7         }
     8         List<Integer> ret = new ArrayList<Integer>();
     9         for (int i = 0; i < n; i++) {
    10             if (nums[i] <= n) {
    11                 ret.add(i + 1);
    12             }
    13             System.out.println("nums:" + i + "," + nums[i]);
    14         }
    15         return ret;
    16     }
    17 }

    ?

    解法二:哈希表

    ?

     1 class Solution {
     2     public List<Integer> findDisappearedNumbers(int[] nums) {
     3         List<Integer> res = new ArrayList<>();
     4         Set<Integer> dic = new HashSet<>();
     5         for(int num : nums) {
     6             dic.add(num);
     7         }
     8 
     9         for(int i= 1; i <= nums.length; i++) {
    10             if(!dic.contains(i)) {
    11                 res.add(i);
    12             }
    13         }
    14         return res;
    15     }
    16 }

    ?

    參考

    找到所有數組中消失的數字 - 力扣(LeetCode) (leetcode-cn.com)

    ?

    本文摘自 :https://www.cnblogs.com/

    開通會員,享受整站包年服務
    国产呦精品一区二区三区网站|久久www免费人咸|精品无码人妻一区二区|久99久热只有精品国产15|中文字幕亚洲无线码