↓快轉到主要內容
  1. LeetCode/

LeetCode 1814: Count Nice Pairs in an Array

·1 分鐘· ·
LeetCode Medium Array Hash-Table Math Counting
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2024-04-17

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

條件 nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) 移項後是 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]):兩邊各自只跟自己有關。所以把每個數換成 x - rev(x),同一個值有 c 個就有 c(c - 1) / 2 對(Hash Table 模板一,也是 Math 模板一的配對數)。答案要對 10^9 + 7 取模。

我的嘗試
#

第一版的作法就對了,但忘了取模,答案很大時 WA;加上 % 1000000007 就 AC 了。

正確解法
#

class Solution:
    def countNicePairs(self, nums: List[int]) -> int:
        cnt = Counter(x - int(str(x)[::-1]) for x in nums)
        return sum(c * (c - 1) // 2 for c in cnt.values()) % (10**9 + 7)

複雜度
#

時間 O(n log M),空間 O(n)。

要特別避免的錯誤
#

  • 題目要求取模。
  • 兩兩比較是 O(n²),要先移項讓每一邊只跟一個 index 有關。

面試口說整理
#

我把條件移項成 nums[i] - rev(nums[i]) 等於 nums[j] - rev(nums[j]),這樣每個數可以各自算出一個 key,同一個 key 有 c 個就有 c 取 2 對,最後取模。時間 O(n log M)。

相關文章

LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·1 分鐘
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 解題筆記:分別數 Y 上和 Y 外每個值的次數,枚舉 Y 的值 a 和背景的值 b(a != b),取最少要改的格子數
LeetCode 229: Majority Element II
·1 分鐘
LeetCode Medium Array Hash-Table Sorting Counting
LeetCode 229 解題筆記:超過 n / 3 的數最多兩個;Boyer-Moore 維護兩個候選人,最後再掃一次確認次數
LeetCode 914: X of a Kind in a Deck of Cards
·1 分鐘
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 解題筆記:每種卡片的張數都要能被同一個 X >= 2 整除,也就是所有張數的 GCD >= 2
LeetCode 313: Super Ugly Number
·1 分鐘
LeetCode Medium Array Math Dynamic-Programming
LeetCode 313 解題筆記:LC 264 的推廣,每個質數一個指針;用 heap 的話要避免同一個數被推進去很多次
LeetCode 396: Rotate Function
·1 分鐘
LeetCode Medium Array Math Dynamic-Programming
LeetCode 396 解題筆記:F(k) 和 F(k - 1) 只差一個公式:F(k) = F(k - 1) + sum - n × 被移到最前面的那個數
LeetCode 264: Ugly Number II
·1 分鐘
LeetCode Medium Hash-Table Math Dynamic-Programming Heap-Priority-Queue
LeetCode 264 解題筆記:三個指針分別指向下一個要乘 2、3、5 的醜數,每次取最小的,相等的指針都要前進