Re: [閒聊] 每日leetcode
https://leetcode.com/problems/number-of-equivalent-domino-pairs/
1128. Number of Equivalent Domino Pairs
給你一個陣列dominoes[i] = [a, b]表示多米諾骰子,對多米諾骰子來說 [a,b] = [b,a]
,求出共有幾對相等的多米諾骰子。
思路:
1.用map記錄多米諾骰子的數量,然後統一點數比較小或大的在前 ([7,5]被當成[5,7]
2.找出所有牌的數量後,如果大於一張牌,任取兩個並總和就是解了。
Java Code:
-------------------------------------
class Solution {
public int numEquivDominoPairs(int[][] dominoes) {
int res = 0;
int[][] cnt = new int[10][10];
for (int[] domino : dominoes) {
int top = domino[0];
int bottom = domino[1];
if (top >= bottom) {
cnt[top][bottom]++;
} else {
cnt[bottom][top]++;
}
}
for (int i = 0; i < cnt.length; i++) {
for (int j = 0; j < cnt.length; j++) {
if (cnt[i][j] > 1) {
res += (cnt[i][j] * cnt[i][j] - cnt[i][j])/2;
}
}
}
return res;
}
}
-------------------------------------
--
https://i.imgur.com/Gh7C9bI.jpeg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.104.111 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1746330847.A.A5B.html
討論串 (同標題文章)
完整討論串 (本文為第 1414 之 1548 篇):