728x90
오늘의 문제
LeetCode - Number of Good Pairs (출처 하단 표기)
문제
Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
제한사항
- 1 <= nums.length <= 100
- 1 <= nums[i] <= 100
입출력 예
nums | return |
[1,2,3,1,1,3] | 4 |
[1,1,1,1] | 6 |
[1,2,3] | 0 |
풀이
import java.util.*;
class Solution {
public int numIdenticalPairs(int[] nums) {
int answer = 0;
Map<Integer, Integer> map = new HashMap<>();
// 숫자: 개수
for(int i=0; i<nums.length; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
for(Map.Entry entry: map.entrySet()) {
int n = (int) entry.getValue();
answer += n*(n-1)/2;
}
return answer;
}
}
같은 숫자의 짝이 몇 개 있는지 반환하는 문제였다. Map을 통해 각 숫자가 몇 개 있는지 저장하고, 조합을 이용해 짝의 개수를 리턴하였다.
출처: LeetCode, https://leetcode.com/problems/number-of-good-pairs/
728x90
'코딩테스트 연습 > 99클럽' 카테고리의 다른 글
[99클럽] 99클럽 코테 스터디 29일차 TIL - 문자열 (0) | 2024.06.17 |
---|---|
[99클럽] 99클럽 코테 스터디 28일차 TIL - 배열 (Array) (0) | 2024.06.16 |
[99클럽] 99클럽 코테 스터디 26일차 TIL - 배열 (Array) (0) | 2024.06.14 |
[99클럽] 99클럽 코테 스터디 25일차 TIL - 그래프 (Graph) (0) | 2024.06.13 |
[99클럽] 99클럽 코테 스터디 24일차 TIL - 그래프 (Graph) (0) | 2024.06.12 |