Algorithm
Problem Name: 961. N-Repeated Element in Size 2N Array
You are given an integer array nums
with the following properties:
nums.length == 2 * n
.nums
containsn + 1
unique elements.- Exactly one element of
nums
is repeatedn
times.
Return the element that is repeated n
times.
Example 1:
Input: nums = [1,2,3,3] Output: 3
Example 2:
Input: nums = [2,1,2,5,3,2] Output: 2
Example 3:
Input: nums = [5,1,5,2,5,3,5,4] Output: 5
Constraints:
2 <= n <= 5000
nums.length == 2 * n
0 <= nums[i] <= 104
nums
containsn + 1
unique elements and one of them is repeated exactlyn
times.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int repeatedNTimes(int[] nums) {
for (int i = 1; i < = 3; i++) {
for (int j = 0; j < nums.length - i; j++) {
if (nums[j] == nums[j + i]) {
return nums[j];
}
}
}
return -1;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const repeatedNTimes = function(A) {
const checkerSet = new Set();
for (let num of A){
if (!checkerSet.has(num)){
checkerSet.add(num);
} else{
return num;
}
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
return collections.Counter(A).most_common(1)[0][0]
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System.Collections.Generic;
namespace LeetCode
{
public class _0961_NRepeatedElementInSize2NArray
{
public int RepeatedNTimes(int[] A)
{
var set = new HashSet < int>();
foreach (var num in A)
{
if (set.Contains(num))
return num;
else
set.Add(num);
}
return -1;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output