소프트웨어에 대한 모든 것

LeetCode 풀기 - 2053. Kth Distinct String in an Array 본문

알고리즘/LeetCode

LeetCode 풀기 - 2053. Kth Distinct String in an Array

앤테바 2021. 12. 13. 20:40
반응형

2053. Kth Distinct String in an Array

https://leetcode.com/problems/kth-distinct-string-in-an-array/

 

Kth Distinct String in an Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) dict 사용

class Solution:
    def kthDistinct(self, arr: List[str], k: int) -> str:
        d = {}
        for i, n in enumerate(arr):
            if n in d:
                d[n][1] += 1
            else:
                d[n] = [i+1, 1]
        
        unique = [k for k, v in d.items() if v[1] == 1]
        if len(unique) >= k:
            return unique[k-1]
        return ''

솔루션2) Counter 객체 사용

class Solution:
    def kthDistinct(self, arr: List[str], k: int) -> str:
        counter = Counter(arr)
        for c in arr:
            if counter[c] == 1:
                k -= 1
            if k == 0:
                return c
        return ''

 

반응형
Comments