[Swift Weekly Contest 116]LeetCode961. 重复 N 次的元素 | N-Repeated Element in Size 2N Array

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

在大小为 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

提示:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. A.length 为偶数

280ms
 1 class Solution {
 2     func repeatedNTimes(_ A: [Int]) -> Int {
 3         var set:Set<Int> = Set<Int>()
 4         for x in A
 5         {
 6             if set.contains(x)
 7             {
 8                 return x
 9             }
10             set.insert(x)
11         }
12         return -1
13     }
14 }

300ms 

 1 class Solution {
 2     func repeatedNTimes(_ A: [Int]) -> Int {
 3         var n:Int = A.count
 4         var f:[Int] = [Int](repeating:0,count:100000)
 5         for v in A
 6         {
 7             f[v] += 1
 8         }
 9         
10         for i in 0..<100000
11         {
12             if f[i] > 1
13             {
14                 return i
15             }
16         }
17         return -1
18     }
19 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10165080.html