leetcode-1590-使数组和能被P整除

 

 

 

 

 

 方法一:

INF = 1 << 60
class Solution:
    def minSubarray(self, A: List[int], p: int) -> int:
        idx = {}
        n = len(A)
        S = [0] * (n + 1)
        for i in range(n):
            S[i + 1] = S[i] + A[i]
        s = S[-1] % p
        if s == 0:
            return 0
        
        ans = INF
        for i, v in enumerate(S):
            l = (v - s) % p
            if l in idx:
                ans = min(ans, i - idx[l])
            idx[v % p] = i
        
        if ans == INF or ans == n:
            ans = -1
        return ans

 

posted @ 2020-09-22 12:25  oldby  阅读(200)  评论(0编辑  收藏  举报