zoukankan      html  css  js  c++  java
  • Leetcode 1590. Make Sum Divisible by P

    Description

    Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
    
    Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
    
    A subarray is defined as a contiguous block of elements in the array.
    

    Example

    Input: nums = [3,1,4,2], p = 6
    Output: 1
    Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
    

    code

    class Solution(object):
        def minSubarray(self, nums, p):
            """
            :type nums: List[int]
            :type p: int
            :rtype: int
            """
            memo = {}
            presum, L, N = 0, float('inf'), len(nums)
            remain = sum(nums) % p
            if remain == 0:
                return 0
            
            memo[0] = -1
            for i, v in enumerate(nums):
                if v == remain:
                    return 1
                
                presum += v
                presum %= p
                
                if presum - remain in memo:
                    L = min(L, i - memo[presum-remain])
                if presum + p -remain in memo:
                    L = min(L, i - memo[presum+p-remain])
            
                memo[presum] = i
            if L == N:
                return -1
            
            return -1 if L == float('inf') else L
    
    
    
    本题调试了很久,原因有2点。第一点,我同余计算总是出错(数学不好啊)。第二点,memo【0】 = 1 这个初始化条件一直没有想到
    
  • 相关阅读:
    二进制、八进制、十进制、十六进制的转换
    loadrunner-检查点
    loadrunner-集合点
    loadrunner-事务
    软件测试分类总结
    《黑客与画家》读后感
    说两个我在工作中有价值的bug
    HTTP状态码
    Android开发学习——android与服务器端数据交互
    Android开发学习——Volley框架
  • 原文地址:https://www.cnblogs.com/tmortred/p/14492858.html
Copyright © 2011-2022 走看看