leetcode961. N-Repeated Element in Size 2N Array

Easy题目
题目链接
题目:
在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。
返回重复了 N 次的那个元素。

示例 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 为偶数
思路:很简单很暴力,用hashmap记录每个元素及其对应的出现次数,如果出现次数等于目标次数了,就直接返回… 后来一想,不一定非要等于目标次数,只要大于1就可以返回,速度果然快了很多。

class Solution {
    public int repeatedNTimes(int[] A) {
        int target = A.length / 2;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int x : A){
            int count = map.getOrDefault(x, 0) + 1;
            map.put(x, count);
            if(count == target){
                return x;
            }
        }
        return 0;
    }
}

优化:

class Solution {
    public int repeatedNTimes(int[] A) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int x : A){
            int count = map.getOrDefault(x, 0) + 1;
            map.put(x, count);
            if(count > 1){
                return x;
            }
        }
        return 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值