1497.check-if-array-pairs-are-divisible-by-k
題目
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return true If you can find a way to do that or false otherwise.
翻譯
輸入會給一個長度為偶數的陣列 n 及整數 k,將陣列分為 n / 2 個組合,判斷是否每個組合的和都可以被 k 整除,是的話回傳 true,不是的話回傳 fasle。
Example:
思路
一、極限值/特殊狀況
陣列元素可能會有 0 或是負數的情況。
二、哪種資料結構解
hash table + counter
三、大概會怎麼解
若某數可以被 k 整除,某數 + k 一定也可以。
把陣列元素都縮小為 ÷ k 的餘數,當作 hash table 的 key,若為負數則 + k 轉為正整數,值為出現次數。
遍歷陣列,並檢查 hash table 中是否有可以配對的數字 (k - hash 值)。
最後檢查是否有達到匹配次數 arr.length / 2。
型別
解題
Last updated