1512. Number of Good Pairs

Yunes·2023년 10월 3일
0
post-thumbnail

문제

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 <= 100
1 <= nums[i] <= 100

작성한 코드

/**
 * @param {number[]} nums
 * @return {number}
 */

// time O(n) space O(n)
var numIdenticalPairs = function(nums) {
  const set = new Set();
  const obj = new Object();
  let output = 0;

  nums.map((num) => {
      // set 에 등록되지 않았다면
      if (!set.has(num)) {
        set.add(num);
        obj[num] = 1;
      } else { // set 에 등록되어 있다면 
        obj[num] += 1;
      }
  })

  Object.keys(obj).map((key) => {
    let n = obj[key];
    output += n * (n - 1) / 2;
  })

  return output
};

아이디어

Set() 을 통해 중복 여부를 체크하고 Object 에 키로 등록한다. 만약 중복일 경우 해당 키에 value 값을 1 증가하여 각 key 가 몇개 존재하는지 파악한다.

이후 key 가 존재하는 수를 nC2 취하여 전체 good pairs 수를 구한다.

profile
미래의 나를 만들어나가는 한 개발자의 블로그입니다.

0개의 댓글