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 这个初始化条件一直没有想到
    
  • 相关阅读:
    fmt命令
    wc命令
    grep命令
    head命令
    C/C++语法知识:typedef struct 用法详解
    邻接表无向图的介绍
    邻接矩阵无向图的介绍
    图的基本概念
    careercup-栈与队列 3.6
    careercup-栈与队列 3.5
  • 原文地址:https://www.cnblogs.com/tmortred/p/14492858.html
Copyright © 2011-2022 走看看