[LeetCode] Number of Good Pairs
Coding Test

[LeetCode] Number of Good Pairs

https://leetcode.com/problems/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.
 
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
 
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100

매우 쉬운 난이도의 문제입니다. 배열에서 같은 값이 있는 쌍을 구하는 것이네요.

시간 복잡도를 고려해서 어떻게 빠른 속도로 계산이 가능할까 했는데, 일단 for loop 중첩을 사용하기로 했습니다.

 

결과는 성공이네요.

 

public class NumberOfGoodPairs {
    public static int solution(int[] nums) {
        int result = 0;

        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    result++;
                }
            }
        }

        return result;
    }
}