LeetCode33|寻找重复数

时间:2022-07-23
本文章向大家介绍LeetCode33|寻找重复数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

2,示例

示例 1:

输入: [1,3,4,2,2]
输出: 2
示例 2:

输入: [3,1,3,4,2]
输出: 3
说明:
不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。

 

3,题解思路

HashSet集合的使用;HashMap键值对集合的使用

4,题解程序


import java.util.HashMap;
import java.util.HashSet;

public class FindDuplicateTest {
    public static void main(String[] args) {
        int[] array = {3, 1, 3, 4, 2};
        int num = findDuplicate(array);
        System.out.println("num = " + num);
        int num2 = findDuplicate2(array);
        System.out.println("num2 = " + num2);

    }

    public static int findDuplicate(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int length = nums.length;
        HashSet<Integer> set = new HashSet<>(length);
        for (Integer num : nums
        ) {
            boolean flag = set.add(num);
            if (!flag) {
                return num;
            }
        }
        return 0;
    }

    public static int findDuplicate2(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (Integer num : nums
        ) {
            hashMap.put(num, hashMap.getOrDefault(num, 0) + 1);
        }
        return hashMap.entrySet().stream().filter(x -> x.getValue() > 1).findFirst().get().getKey();
    }
    
    public static int findDuplicate3(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (Integer num : nums) {
            if (hashMap.containsKey(num)) {
                return num;
            } else {
                hashMap.put(num, 1);
            }
        }
        return 0;
    }
}

5,题解程序图片版

6,总结

每次总结都不知道要说什么,因为题解思路给的很清楚,使用什么的方式来解决,题解程序也清晰,到了总结的时候,就觉得文字的描述在描述就有点...,这样对于读者来说也完全没有那么重要的意义。