일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- heapq
- 그래프
- apache kafka
- 파이썬
- 아파치 스파크
- Kubernetes
- 코딩테스트
- 분산
- 우선순위큐
- 문자열
- 티스토리챌린지
- 오블완
- 이진탐색
- programmers
- Apache Spark
- Python
- 분산처리
- DP
- docker
- 리트코드
- 쿠버네티스
- String
- leetcode
- Apache Hadoop
- 프로그래머스
- 아파치 하둡
- BFS
- 아파치 카프카
- 도커
- 알고리즘
- Today
- Total
래원
[LeetCode] 2364. Count Number of Bad Pairs (Python) 본문
난이도: Medium
문제 설명
You are given a 0-indexed integer array nums
. A pair of indices (i, j)
is a bad pair if i < j
and j - i != nums[j] - nums[i]
.
Return the total number of bad pairs in nums
.
문제 예제
Example 1:
Input: nums = [4,1,3,3]
Output: 5
Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
There are a total of 5 bad pairs, so we return 5.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 0
Explanation: There are no bad pairs.
제한 사항
1 <= nums.length <= 105
1 <= nums[i] <= 109
✏️ Solution(솔루션)
class Solution:
def countBadPairs(self, nums: List[int]) -> int:
n = len(nums)
c = defaultdict(int)
answer = n * (n-1)//2
for i in range(n):
c[nums[i] - i] += 1
for k, v in c.items():
if v > 1:
answer -= v*(v-1)//2
return answer
문제 설명에서 bad pair의 기준은 i<j일 때, j - i != nums[j] - nums[i] 라고 했다.
이를 다시 써보면 nums[i] - i != nums[j] - j로 표현할 수 있다.
따라서, nums의 요소를 탐색하면서 nums[i] - i의 값을 세었다.
왜냐하면 이 값을 동일하게 갖는 요소들의 개수를 세면 이들이 (i, j) 쌍을 이룰 때 good pair가 되기 때문이다.
이제, 전체 쌍의 개수에서 good pair의 개수를 빼면 bad pair의 개수를 구할 수 있다.
전체 쌍의 개수는 조합 공식인 n * (n-1) / 2 를 이용해 구할 수 있다.
그리고 good pair의 개수는 같은 nums[i] - i 값을 갖는 요소들의 개수를 v라고 했을 때, v * (v-1) / 2 로 계산된다.
결과적으로, nums를 순회하며 nums[i] - i 값을 세고, 이를 기반으로 good pair의 개수를 구한 후 전체 쌍에서 빼주는 방식으로 문제를 해결했다.
문제: 2364. Count Number of Bad Pairs
깃허브: github
algorithmPractice/LeetCode/2448-count-number-of-bad-pairs at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 1910. Remove All Occurrences of a Substring (Python) (0) | 2025.02.11 |
---|---|
[LeetCode] 3174. Clear Digits (Python) (0) | 2025.02.10 |
[LeetCode] 2349. Design a Number Container System (Python) (0) | 2025.02.08 |
[LeetCode] 3160. Find the Number of Distinct Colors Among the Balls (Python) (0) | 2025.02.07 |
[LeetCode] 1726. Tuple with Same Product (Python) (0) | 2025.02.06 |