N-Repeated Element In Size 2N Array Problem


Description

LeetCode Problem 961.

In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

Return the element repeated N times.

Example 1:

1
2
Input: [1,2,3,3]
Output: 3

Example 2:

1
2
Input: [2,1,2,5,3,2]
Output: 2

Example 3:

1
2
Input: [5,1,5,2,5,3,5,4]
Output: 5


Sample C++ Code

This is a C++ solution using a hash table. The time complexity is O(n), and the space complexity is O(n).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

int repeatedNTimes(vector<int>& A) {
    int len = A.size();
    int n = len / 2;
    map<int, int> ht;
    for (int i = 0; i < len; i ++) {
        if (ht.find(A[i]) == ht.end())
            ht[A[i]] = 0;
        ht[A[i]] ++;
        if (ht[A[i]] > 1)
            return A[i];
    }
    return ht[A[len-1]];
}

int main() {
    vector<int> A = {1, 2, 3, 3};
    cout << repeatedNTimes(A) << endl;
}




Related Posts

Repeated DNA Sequences Problem

LeetCode 187. The DNA sequence is composed of a series...

Majority Element Problem

LeetCode 169. Given an array nums of size n, return...

Fraction To Recurring Decimal Problem

LeetCode 166. Given two integers representing the numerator and denominator...

Max Points On A Line Problem

LeetCode 149. Given an array of points where points[i] =...

Lru Cache Problem

LeetCode 146. Design a data structure that follows the constraints...

Longest Consecutive Sequence Problem

LeetCode 128. Given an unsorted array of integers nums, return...