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

LeetCode 2176: Count Equal and Divisible Pairs in an Array

·1 分鐘· ·
LeetCode Easy Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-04-17

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

n <= 100,直接枚舉所有 i < j 的配對(Array 模板四)。兩個條件:nums[i] == nums[j],而且 index 的乘積 i * j 能被 k 整除。

我的嘗試
#

第一版寫成 (nums[i] * nums[j]) // 2,用了值、而且用整數除以 2 當條件。例如 nums = [1, 1]、k = 4:0 × 1 = 0 能被 4 整除,答案 1;這版算 1 × 1 // 2 = 0,是 False,回傳 0。改成 not (i * j) % k 就 AC 了。

正確解法
#

class Solution:
    def countPairs(self, nums: List[int], k: int) -> int:
        n = len(nums)
        return sum(nums[i] == nums[j] and i * j % k == 0
                   for i in range(n) for j in range(i + 1, n))

複雜度
#

時間 O(n²),空間 O(1)。

要特別避免的錯誤
#

  • 乘積用的是 index,不是值。
  • 「能被 k 整除」是 % k == 0。

面試口說整理
#

n 很小,我枚舉所有配對,檢查值相等而且 index 的乘積能被 k 整除。時間 O(n²)。

相關文章

LeetCode 1431: Kids With the Greatest Number of Candies
·1 分鐘
LeetCode Easy Array
LeetCode 1431 解題筆記:先算一次最大值,每個人加上額外的糖果後 >= 最大值就是 True;平手也算最多
LeetCode 3487: Maximum Unique Subarray Sum After Deletion
·1 分鐘
LeetCode Easy Greedy Hash-Table Array
LeetCode 3487 解題筆記:可以任意刪除,所以等於挑不重複的值;非負的全拿,全是負數時只拿最大的一個
LeetCode 3507: Minimum Pair Removal to Sort Array I
·1 分鐘
LeetCode Easy Simulation Array
LeetCode 3507 解題筆記:n 很小直接模擬,切片賦值右邊要是 list
LeetCode 3131: Find the Integer Added to Array I
·1 分鐘
LeetCode Easy Array
LeetCode 3131 解題筆記:每個數都加上同一個 x,所以 x 就是兩個陣列最小值的差(或總和的差除以長度)
LeetCode 3074: Apple Redistribution into Boxes
·1 分鐘
LeetCode Easy Array Greedy Sorting
LeetCode 3074 解題筆記:箱子可以隨便分,所以從容量最大的箱子開始拿,總容量夠裝所有蘋果就停
LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 解題筆記:選出最大的 k 個數(連同 index),再按 index 排回原本的順序