Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6 Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3] Output: 0
class Solution {
    public int numIdenticalPairs(int[] nums) {
        /*
        배열 내 같은 수의 Count를 구하기
        1<= nums.length <= 100
        1 <= nums[i] <= 100
        Counting sort?
        괜찮을듯? ㄱㄱ
        
        */
        int result = 0;
        int[] countArr = new int[100];
        
        for(int idx : nums) {
            countArr[nums[idx]]++;
            
        }
        
        for(int idx : countArr) {
            int temp = countArr[idx];
            System.out.println(temp / 2 * (temp - 1));
            countArr[idx] = temp / 2 * (temp - 1);
        }
        
        for(int idx : countArr) {
            result += countArr[idx];
        }
        
        return result;
    }
}
결과가 원하는대로 안나옴 ㅠ계수정렬 찾아보니 이렇게 해결
class Solution {
    public int numIdenticalPairs(int[] nums) {
        /*
        배열 내 같은 수의 Count를 구하기
        1<= nums.length <= 100
        1 <= nums[i] <= 100
        Counting sort?
        괜찮을듯? ㄱㄱ
        
        */
        
        int[] countArr = new int[101];
        int result = 0;
        for(int idx = 0; idx < nums.length; idx++) {
            result += countArr[nums[idx]];
            ++countArr[nums[idx]];
            
        }
        return result;
    }
}HashMap으로
import java.util.HashMap;
class Solution {
    public int numIdenticalPairs(int[] nums) {
        HashMap<Integer, Integer> hs = new HashMap<>();
        int count = 0;
        for (int n : nums) {
            if (hs.containsKey(n)) {
                int k = hs.get(n);
                count += k;
                hs.put(n, k + 1);
            } else {
                hs.put(n, 1);
            }
        }
        return count;
    }
}
'Algorithm > LeetCode' 카테고리의 다른 글
| [LeetCode] Jewels and Stones (0) | 2021.06.18 | 
|---|---|
| [LeetCode] Kids With the Greatest Number of Candies (0) | 2021.06.16 | 
| [LeetCode] Kids With the Greatest Number of Candies (0) | 2021.06.14 | 
| [LeetCode] Richest Customer Wealth (0) | 2021.06.12 | 
| [LeetCode] Shuffle the Array (0) | 2021.06.11 |