https://leetcode.com/problems/unique-number-of-occurrences/
문제: 숫자로 이루어진 배열에서 각 원소의 갯수가 중복되는지 판별하는 문제
문제 설명:
문제에서 주어진 예시로 설명을 해보겠습니다.
예제 1번을 보면, [1, 2, 2, 1, 1, 3] 이라는 배열이 있습니다.
원소 1은 3개, 원소 2는 2개, 원소 3은 1개로 각 원소의 갯수가 중복되지 않으므로 True를 반환해줍니다.
예제 2번을 보면, 원소 1과 2가 둘다 1로 원소의 갯수가 중복이 되므로 False를 반환해줍니다.
저는 이 문제를 파이썬의 Counter 함수를 통해서 풀었는데, Counter 함수를 사용하게 되면 다음과 같은 결과가 나옵니다
from collections import Counter
arr= [1,2,2,1,1,3]
print(Counter(arr))
# 출력한 결과
# Counter({1: 3, 2: 2, 3: 1})
Counter를 쓰면 key-value 쌍으로 counter 형의 데이터가 만들어집니다.
이를 바탕으로, value 값들을 통해 중복된 값이 있는지 여부를 판별해주었습니다.
풀이 코드:
from collections import Counter
from collections import deque
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
cntarr = Counter(arr)
counterval = deque(cntarr.values())
while counterval:
v = counterval.pop()
if v in counterval:
return False
return True
'알고리즘 > Leetcode' 카테고리의 다른 글
[Leetcode /python] 530. Minimum Absolute Difference in BST (0) | 2022.11.21 |
---|---|
[Leetcode / python] 777번,2337번 공통 풀이 (0) | 2022.11.17 |
[Leetcode / python] 2079. Watering Plants (0) | 2022.11.16 |
[Leetcode / python] 2. Add Two Numbers (0) | 2022.11.15 |
[Leetcode / python] 1652. Defuse the Bomb (0) | 2022.11.14 |