LeetCode59|重复N次的元素

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

1,问题简述

在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。

返回重复了 N 次的那个元素。

2,示例

示例 1:

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

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

输入:[5,1,5,2,5,3,5,4]
输出:5
 

提示:

4 <= A.length <= 10000
0 <= A[i] < 10000
A.length 为偶数

 

3,题解思路

键值对集合,HashSet集合的使用

4,题解程序


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

public class RepeatedNTimesTest {
    public static void main(String[] args) {
        int[] A = {1, 2, 3, 3};
        int repeatedNTimes = repeatedNTimes2(A);
        System.out.println("repeatedNTimes = " + repeatedNTimes);
    }

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

    public static int repeatedNTimes2(int[] A) {
        if (A == null || A.length < 4) {
            return -1;
        }
        HashSet<Integer> hashSet = new HashSet<>();
        for (int j : A) {
            if (!hashSet.add(j)) {
                return j;
            }
        }
        return -1;
    }
}

5,题解程序图片版

6,总结

写了一年的文章了,整体输出文章内容基本上都是以java为主,大概篇幅内容都是围绕着数据库,JDK源码,mybatis,spring,springboot的框架来进行输出的,一年有所成长,有所失去,快到十一了,去年也是十一的时候开始了文章输出的,一年的时间过得好快啊