[LeetCode] Count Equal and Divisible Pairs in an Array

준규·2022년 12월 18일

1.문제


Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.


0 index 정수 배열이 주어질 때 0 <= i < j < n인 인덱스 조건에서 nums[i] == nums[j] 인 i , j 의 곱이 k에 나누어지는 경우의 수를 리턴하는 문제이다.


Example 1

Input: nums = [3,1,2,2,2,1,3], k = 2
Output: 4
Explanation:
There are 4 pairs that meet all the requirements:
- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.
- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.
- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.
- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.

### Example 2
Input: nums = [1,2,3,4], k = 1
Output: 0
Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i], k <= 100

2.풀이

  1. 배열의 앞에서부터 두개씩 배열 요소값을 비교한다.
  2. nums[i] === nums[j] 이고 i*j 가 k에 나누어떨어지면 count + 1

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
const countPairs = function (nums, k) {
  let count = 0;
  for (let i = 0; i < nums.length - 1; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      // 배열의 앞에서부터 두개씩 비교
      if (nums[i] === nums[j]) {
        // 두 숫자 값이 동일하고
        if ((i * j) % k === 0) {
          // i*j 가 k 로 나누어지면 count + 1
          count++;
        }
      }
    }
  }

  return count;
};

3.결과

profile
안녕하세요 :)

0개의 댓글