728x90
난이도 : medium
리스트 nums에서 (j > i) num[j] -num[i] != j - i인 쌍을 찾는 문제
리스트 nums에서 2개의 요소로 이루어진 total 수에서 num[j] -num[i] = j - i 인 쌍을 빼면 될 것.
num[j] - j = num[i] - i = a라고 해석할 수 있는데,
이 a값으로만 이루어진 요소가 몇 개인지 count 후 count * (count -1 ) / 2를 취한 값을 sum하면 풀린다.
from collections import Counter
class Solution:
def countBadPairs(self, nums: List[int]) -> int:
n = len(nums)
total = n * (n - 1)// 2
count = Counter([nums[i] - i for i in range(n)])
return total - sum([(val - 1) * val // 2 for key, val in count.items() if val > 1])
- total = n * (n - 1) // 2
- nums[i] - i를 Counter 취함
- count 딕셔너리에서 val값이 1 초과인 값으로 이루어진 요소의 갯수를 일일히 sum한 후, total에서 빼줌
Runtime : 55ms (96.98%)
Memory : 39.30MB (8.95%)
728x90
'코딩 공부 > Leetcode' 카테고리의 다른 글
[Leetcode / Python] 2375. Construct Smallest Number From DI String (0) | 2025.02.18 |
---|---|
[Leetcode / Python] 3066. Minimum Operations to Exceed Threshold Value II (0) | 2025.02.13 |
[Leetcode / Python] 3174. Clear Digits (0) | 2025.02.12 |
[Leetcode / Python] 1910. Remove All Occurrences of a Substring (0) | 2025.02.11 |
[Python] 206. Reverse Linked List (0) | 2025.02.11 |