力扣【448】找到所有数组中消失的数字

题目:

给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

题解:
 

import java.util.*;

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return list;
        }
        int length = nums.length;
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < length; i++) {
            set.add(nums[i]);
        }
        for (int i = 1; i <= length; i++) {
            if (!set.contains(i)) {
                list.add(i);
            }
        }
        return list;
    }
}

public class Main {
    public static void main(String[] args) {
        int[] nums = {4,3,2,7,8,2,3,1};
        Solution solution = new Solution();
        List<Integer> res = solution.findDisappearedNumbers(nums);
        System.out.println("结果:" + res);
    }
}

猜你喜欢

转载自blog.csdn.net/qq1922631820/article/details/112123474