Back to Leetcode Go

961. N-Repeated Element in Size 2N Array

website/content.en/ChapterFour/0900~0999/0961.N-Repeated-Element-in-Size-2N-Array.md

1.7.971.2 KB
Original Source

961. N-Repeated Element in Size 2N Array

Problem

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:

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

Example 2:

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

Example 3:

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

Note:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A.length is even

Problem Summary

In an array A of size 2N, there are N+1 distinct elements, and one of these elements is repeated N times. Return the element repeated N times.

Solution Approach

  • Easy problem. There are 2N numbers in the array, and N + 1 numbers are unique. Among them, one number is repeated N times; find this number. The solution is very simple: store all numbers in a map, and if an existing key is encountered, return that number.

Code

go

package leetcode

func repeatedNTimes(A []int) int {
	kv := make(map[int]struct{})
	for _, val := range A {
		if _, ok := kv[val]; ok {
			return val
		}
		kv[val] = struct{}{}
	}
	return 0
}