본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 1128. Number of Equivalent Domino Pairs

반응형

https://leetcode.com/problems/number-of-equivalent-domino-pairs/description/

 

Number of Equivalent Domino Pairs - LeetCode

Can you solve this real interview question? Number of Equivalent Domino Pairs - Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can

leetcode.com

자료구조를 이용한 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 도미노 정보를 key로, 해당 정보의 빈도수를 value로 저장할 map 변수 countMap을 선언해줍니다.2. 정답 변수 ans를 선언해줍니다.

📔 풀이과정

dominoes원소를 순회합니다.

1. 기존 패턴의 도미노가 나왔다면 counMap의 value만큼의 pair가 새롭게 생깁니다. 따라서 countMap의 value값을 ans에 누적해 더해줍니다.

2. 새로운 패턴의 도미노 또는 기존 패턴의 도미노가 나오든 countMap의 value를 1씩 증가시켜줍니다. 초기화를 따로 하지 않아도 value는 0부터 시작하므로 새롭게 나왔다면 1이 되며 기존 패턴이라면 해당값을 1증가 시켜줄 것입니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int numEquivDominoPairs(vector<vector<int>>& dominoes) {
        map <pair<int,int>, int> countMap;
        int ans = 0;
        for(auto d : dominoes) {
            int a = min(d[0], d[1]);
            int b = max(d[0], d[1]);
            if (countMap.find({a,b}) != countMap.end()) {
                ans+= countMap[{a,b}];
            }
            countMap[{a,b}]++;
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.