728x90
▼ 문제 바로가기 (링크) ▼
https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/
Count Number of Pairs With Absolute Difference K - 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
정수 배열 nums와 정수 k가 주어진다.
nums에서 (i,j) 형태로 조합했을 때, 절대값이 k인 경우의 수를 반환하는 문제.
from itertools import combinations # 조합 함수 임포트
class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
comb = list(combinations(nums,2)) # 2개씩 뽑는 조합.
# print(comb) [(1, 2), (1, 2), (1, 1), (2, 2), (2, 1), (2, 1)]
cnt = 0
for i in range(len(comb)):
if abs((comb[i][0] - comb[i][1])) == k: #절대값 함수 abs()
cnt += 1
return cnt
itertools 의 조합 함수로 (i, j) 형태의 새로운 리스트를 만들고
기본 내장함수인 obs()로 절대값을 판별해 cnt 변수에 담아 반환했다.
728x90
반응형
'코딩 테스트 > leetCode' 카테고리의 다른 글
[leetCode] 1816. Truncate Sentence (Python) (0) | 2022.10.24 |
---|---|
[leetCode] 645. Set Mismatch (Python) (0) | 2022.10.23 |
[leetCode] 2418. Sort the People (Python) (0) | 2022.10.21 |
[leetCode]1688. Count of Matches in Tournament (Python) (0) | 2022.10.21 |
[leetCode] 1791. Find Center of Star Graph (Python) (0) | 2022.10.21 |