1. 程式人生 > >[Swift Weekly Contest 116]LeetCode961. 重復 N 次的元素 | N-Repeated Element in Size 2N Array

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

elements HERE 元素 輸入 偶數 () etc length swift

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 }

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