★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pphxcsse-kv.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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 be rotated to be equal to another domino.git
Return the number of pairs (i, j)
for which 0 <= i < j < dominoes.length
, and dominoes[i]
is equivalent to dominoes[j]
.github
Example 1:微信
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] Output: 1
Constraints:app
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9
給你一個由一些多米諾骨牌組成的列表 dominoes
。dom
若是其中某一張多米諾骨牌能夠經過旋轉 0
度或 180
度獲得另外一張多米諾骨牌,咱們就認爲這兩張牌是等價的。ui
形式上,dominoes[i] = [a, b]
和 dominoes[j] = [c, d]
等價的前提是 a==c
且 b==d
,或是 a==d
且 b==c
。spa
在 0 <= i < j < dominoes.length
的前提下,找出知足 dominoes[i]
和 dominoes[j]
等價的骨牌對 (i, j)
的數量。code
示例:htm
輸入:dominoes = [[1,2],[2,1],[3,4],[5,6]] 輸出:1
提示:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9
1 class Solution { 2 func dominoHash(_ dom:[Int]) -> Int { 3 if dom[0] > dom[1] { 4 return 100*dom[1] + dom[0] 5 } 6 return 100*dom[0] + dom[1] 7 } 8 9 func numEquivDominoPairs(_ dominoes: [[Int]]) -> Int { 10 var result = 0 11 var counts = [Int : Int]() 12 13 for d in dominoes { 14 let h = dominoHash(d) 15 if let count = counts[h] { 16 result += count 17 counts[h] = count + 1 18 } else { 19 counts[h] = 1 20 } 21 } 22 return result 23 } 24 }
196ms
1 sample 196 ms submission 2 class Solution { 3 func numEquivDominoPairs(_ dominoes: [[Int]]) -> Int { 4 var originals = [Int]() 5 6 dominoes.forEach { (domino) in 7 originals.append(10*min(domino[0], domino[1]) + max(domino[0], domino[1])) 8 } 9 10 var counts: [Int: Int] = [:] 11 originals.forEach { counts[$0, default: 0] += 1 } 12 13 var count = 0 14 counts.forEach { count = count + ( $1 * ($1 - 1)/2 ) } 15 16 return count 17 } 18 }
200ms
1 class Solution { 2 func numEquivDominoPairs(_ dominoes: [[Int]]) -> Int { 3 let dominoes = dominoes.map { dom -> Int in 4 if dom[0] <= dom[1] { 5 return dom[0] * 10 + dom[1] 6 } else { 7 return dom[1] * 10 + dom[0] 8 } 9 } 10 var counts = [Int: Int]() 11 var res = 0 12 for num in dominoes { 13 res += (counts[num] ?? 0) 14 counts[num, default: 0] += 1 15 } 16 return res 17 } 18 }
Runtime: 224 ms
1 class Solution { 2 func numEquivDominoPairs(_ dominoes: [[Int]]) -> Int { 3 var dominoes = dominoes 4 var freq:[[Int]:Int] = [[Int]:Int]() 5 var total:Int = 0 6 for i in 0..<dominoes.count 7 { 8 if dominoes[i][0] > dominoes[i][1] 9 { 10 dominoes[i].swapAt(0,1) 11 } 12 total += freq[[dominoes[i][0], dominoes[i][1]],default:0] 13 freq[[dominoes[i][0], dominoes[i][1]],default:0] += 1 14 } 15 return total 16 } 17 }