1. 문제(원본)
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:
- 4 <= A.length <= 10000
- 0 <= A[i] < 10000
- A.length is even
2. 문제
2N의 배열에서 배열의 인덱스 수 / 2 의 해당하는 인덱스를 구하라
3. 나의 답
class Solution {
func repeatedNTimes(_ A: [Int]) -> Int {
for element in A where (A.filter { $0 == element }.count > 1) {
return element
}
return 0
}
}
4. 다른 유저의 답
#1
func repeatedNTimes(_ A: [Int]) -> Int {
let mappedItems = A.map { ($0, 1) }
let counts = Dictionary(mappedItems, uniquingKeysWith: +) // key - number, value - count
if let index = counts.values.firstIndex(of: A.count / 2) {
return counts.keys[index]
}
return 0
}
5. 마무리
이번 문제는 어려운 문제는 아니였지만 메모리 적인 문제 때문에 꽤나 애 먹은 문제이다. 범위가 최대 10000이기 때문에 반복문을 사용해도 시간이 꽤 걸리기 때문이다.
이번 문제를 통해 문제를 해결하려는 생각도 좋지만 좀 더 메모리에도 부담이 덜 가는 방향으로 생각을 해야할 것 같다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode728. Self Dividing Numbers (0) | 2020.03.25 |
---|---|
LeetCode700. Search in a Binary Search Tree (0) | 2020.03.23 |
LeetCode617. Merge Two Binary Trees (0) | 2020.03.18 |
LeetCode657. Robot Return to Origin (0) | 2020.03.18 |
LeetCode1266. Minimum Time Visiting All Points (0) | 2020.03.15 |