Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 귤 고르기 #30

Closed
hwangJi-dev opened this issue Nov 25, 2022 · 0 comments
Closed

[Algorithm] 귤 고르기 #30

hwangJi-dev opened this issue Nov 25, 2022 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

💬 문제

[코딩테스트 연습 - 귤 고르기](https://school.programmers.co.kr/learn/courses/30/lessons/138476)


💬 Idea

  • 귤의 개수 중 K개를 고르는데, 최소 종류를 만족하는 종류의 개수를 구하는 문제이다.
  • 따라서 귤의 개수가 많은 순서대로 정렬되도록 배열을 새로 만들어준 후 k개 만큼 배열을 자른 후 Set 함수를 사용하여 최소 개수를 구해주었다.

💬 풀이

func solution(k:Int, tangerine:[Int]) -> Int {
    var tangerineDict: [Int: Int] = [:]

    for i in tangerine {
        if tangerineDict[i] != nil {
            tangerineDict[i]! += 1
        } else {
            tangerineDict[i] = 1
        }
    }
    
    let sortedDitionary = tangerineDict.sorted { $0.1 > $1.1 }
    var sortedTangerine: [Int] = []
    for element in sortedDitionary {
        for _ in 1...element.value {
            sortedTangerine.append(element.key)
        }
    }
    
    let sliceTangerine = sortedTangerine[0..<k]
    return Set(sliceTangerine).count
}

💬 아쉬운 점

  • map, filter, sorted와 같은 고차함수들을 잘 다룬다면 더 간단하게 풀 수 있을 것 같은 문제여서 아쉽다. 더 공부한 뒤에 다시한번 다른 방법으로 풀어보고 싶다 !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant