알고리즘/해결

LeetCode961. N-Repeated Element in Size 2N Array

언클린 2020. 3. 23. 21:00
728x90

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:

  1. 4 <= A.length <= 10000
  2. 0 <= A[i] < 10000
  3. 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이기 때문에 반복문을 사용해도 시간이 꽤 걸리기 때문이다. 

이번 문제를 통해 문제를 해결하려는 생각도 좋지만 좀 더 메모리에도 부담이 덜 가는 방향으로 생각을 해야할 것 같다.

 

728x90