此博客链接:https://www.cnblogs.com/ping2yingshi/p/14056380.html
重复N次的元素
题目链接:https://leetcode-cn.com/problems/n-repeated-element-in-size-2n-array/
题目
在大小为 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 为偶数
题解
思路:使用哈希表,把不同字母当成key,出现的次数作为value,然后判断value中次数等于N的是哪个数字。
方法
1.定义一个哈希表
2.把不同字母存入到哈希表的key中,把对应的次数存到value中。
3.判断value的值是否等于数组长度的一半。
代码
class Solution { public int repeatedNTimes(int[] A) { Map <Integer,Integer> map=new HashMap(); for(Integer tem:A) { Integer count=map.get(tem); if(count==null) map.put(tem,1); else map.put(tem,++count); } for(Integer temp:map.keySet()) { if((int)map.get(temp)==A.length/2) return temp; } return -1; } }
耗时
原因:map中value中的值类型是Integer,而在判断value的值是否等于数组长度一半时,数组长度一半时Int类型的,比较的值类型不一致,导致判断不正确。