Coding Test/LeetCode

[LeetCode] 1512. Number of Good Pairs c++

owls 2022. 10. 10. 17:00
728x90
  • 문제

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.

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.

 

  • 문제 해결
class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        
       int answer(0), len = nums.size();
        
        for(int i = 0; i < len - 1; i++){
            for(int j = i + 1; j < len; j++){
                if(nums[i] == nums[j])
                    answer++;
            }
        }
        return answer;
    }
};

다른 풀이

int numIdenticalPairs(vector<int>& nums) {
     int ans=0;
     unordered_map<int,int>mp;
     for(int &it:nums){
         ans += mp[it]++;
     }
     return ans;
}

 

다른 풀이2

class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        
        int mem[101] ={0};
        int sum=0;
        
        for(int i=0; i < nums.size(); i++){
            sum += mem[nums[i]];
            ++mem[nums[i]];
        }
        
        return sum;
    }
};

 

728x90