Re: [閒聊] 每日leetcode

作者: sustainer123 (caster)   2024-06-09 10:15:47
https://leetcode.com/problems/subarray-sums-divisible-by-k
974. Subarray Sums Divisible by K
給定一數列nums與整數k
請回傳能被k整除的子序列和之非空子序列數量
此子序列必須是nums的連續部分
Example 1:
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Example 2:
Input: nums = [5], k = 9
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104
思路:
這題就昨天那題的變形
昨天用集合紀錄前綴和
今天需要知道子序列數量 所以要改用哈希表
哈希表紀錄該前綴和出現幾次
把它加到result再回傳就結束了
Python Code:
class Solution:
def subarraysDivByK(self, nums: List[int], k: int) -> int:
nums.insert(0,0)
prefix = defaultdict(int)
prefix[0] = 1
result = 0
for i in range(1,len(nums)):
nums[i] = (nums[i]+nums[i-1])%k
result += prefix[nums[i]]
prefix[nums[i]] += 1
return result
作者: Rushia (みけねこ的鼻屎)   2024-06-09 10:25:00
有些語言會被MOD搞 python剛好不會有些語言負數取MOD會是負數
作者: sustainer123 (caster)   2024-06-09 10:26:00
為啥 長度問題?喔喔 原來
作者: Rushia (みけねこ的鼻屎)   2024-06-09 10:26:00
像java -1 % 2 == -1 python是1
作者: sustainer123 (caster)   2024-06-09 10:28:00
我打完週賽用java再寫一次 直覺應該是加個abs

Links booklink

Contact Us: admin [ a t ] ucptt.com