题目链接:961. 在长度 2N 的数组中找出重复 N 次的元素(简单)
算法原理:
解法:哈希表
1ms击败78.59%
时间复杂度O(n)
思路很简单,数组 nums 中有 n+1 个不同的元素,而其长度为 2n,那么剩余的元素均只出现了一次,所以重复出现的元素即为答案
Java代码:
class Solution { public int repeatedNTimes(int[] nums) { Set<Integer> hash=new HashSet<>(); //写法一:hash.add(x)是先判断是否有x再决定是否add //如果有x,直接返回false,!hash.add(x)就是返回true //如果没有x:add(x),然后返回true,!hash.add(x)就是返回false // for(int x:nums) if(!hash.add(x)) return x; //写法二: for(int x:nums){ if(hash.contains(x)) return x; else hash.add(x); } //照顾编译器 return 0; } }