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 这个初始化条件一直没有想到
    
  • 相关阅读:
    Dialog 对话框的文字与输入框不对齐
    ag-grid动态生成表头及绑定表数据
    ag-grid实时监测复选框变化
    Java-分页工具类
    Java-日期转换工具类
    文件上传与下载
    IDEA的安装与激活
    熟悉IDEA工具的使用
    缓存三大问题的解决办法
    制作一个省份的三级联动菜单
  • 原文地址:https://www.cnblogs.com/tmortred/p/14492858.html
Copyright © 2011-2022 走看看