Algorithm

[Leetcode] 2176.Count Equal and Divisible Pairs in an Array

딸기검 2022. 3. 12. 21:09

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.

 

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.

 

난이도: easy

 

같은 숫자인 두개의 index를 곱해서 k로 나누어 지는 경우를 구해라 

 

var countPairs = function(nums, k) {
    // map 생성 { number => [index] }
    const map = new Map();
    let count = 0;
    // for 문 -> map.get(number) ? [index].push : push(index)
    for (let i = 0; i < nums.length; i++) {
        const number = nums[i];
        const getItem = map.get(number);
        
        if (getItem) {
            for (let j = 0; j < getItem.length; j++) {
                const index = getItem[j];
                if ((index * i) % k === 0) count++;
            }
            getItem.push(i);
        } else {
            map.set(number, [i]);
        }
    }
    return count;
};

 

map을 생성해서 같은 숫자인지 확인 -> 곱해서 k로 나누어 떨어지는 확인 

 

두가지로 생각해서 풀이를 했다 hashMap을 사용해서 풀이 

 

언제쯤 easy에서 벗어날 수 있을까 

 

이중 for문으로 푼 경우가 더 효율이 좋은 걸 보고 내가 생각이 짧았구나 싶었다 

이래서 아직 medium은 벽이 느껴지나 보다 

 

 

반응형