[LeetCode] 961. 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.
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length is even
直覺解
構想:
因為陣列中的元素可能是 0,所以不能用正負號來紀錄數字是否出現過,也不能把陣列轉換成 linked list。
從 nums 的第一個元素開始檢查,把出現過的元素記錄下來。若發現有個數字已經出現過,就 return 該數字
javascript 實作:
const repeatedNTimes = function(A) {
const seen = {}
let i = 0
while(i < A.length) {
if (!seen[A[i]]) {
seen[A[i]] = true
} else {
return A[i]
}
i++
}
}
效能:
Runtime: 72 ms, faster than 98.97% of JavaScript online submissions for N-Repeated Element in Size 2N Array.
Memory Usage: 41.8 MB, less than 93.08% of JavaScript online submissions for N-Repeated Element in Size 2N Array.
犯過的低級錯誤:
- 把 seen[A[i]] 寫成 seen.[A[i]]
Comments
Post a Comment