반응형
Problem
이번 문제는 배열 안에 같은 값을가지는 ( i,j ) 쌍이 몇가지 있는지 찾는 문제이다
나의 풀이
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
res = 0
import itertools
a_list = itertools.combinations(nums,2)
for i in a_list:
if i[0] == i[1]:
res += 1
return res
이전에 itertools에 있는 combinations를 사용한 기억을 되살려 저걸 활용해서 문제를 풀었다
itertools.combinations(iterable , r)
combinations는 iterable 한 객체를 r 의 길이를 가진 조합들을 뽑아내준다
ex )
combinations('ABCD', 2) --> AB AC AD BC BD CD
combinations로 nums의 조합들을 구하고 i[0] == i[1] 두 자리의수가 같을때 res + =1 을 하여 문제를 해결했다
또 다른 풀이를 안 볼 수가 없다!
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
#approach -> use a hashmap to store a key value pair of numbers and arr
#when we use arr we can know the number of times that each element has in the array
number_mapping = Counter(nums)
res = 0
for pairs in number_mapping.values():
res += (pairs * (pairs - 1)) // 2
return res
접근 해석
접근 -> 해시 맵을 사용하여 키 값 쌍의 숫자와 배열을 저장합니다.
우리가 배열을 사용할 때 우리는 각 요소가 배열에 있는 횟수를 알 수 있다.
옳게된 좋은 사고
반응형
'Python > algorithm' 카테고리의 다른 글
[Leetcode] 771. Jewels and Stones (0) | 2022.12.27 |
---|---|
[Leetcode] 1672. Richest Customer WealthEasy2.9K305 (0) | 2022.12.26 |
[Leetcode] 1470. Shuffle the Array (1) | 2022.12.21 |
[Leetcode] 2011. Final Value of Variable After Performing Operations (1) | 2022.12.20 |
[Leetcode] 480. Running Sum of 1d Array (1) | 2022.12.19 |