LeetCode1590. Make Sum Divisible by P

文章目录

一、题目

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 1:

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.
Example 2:

Input: nums = [6,3,5,2], p = 9
Output: 2
Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.
Example 3:

Input: nums = [1,2,3], p = 3
Output: 0
Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.

Constraints:

1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= p <= 109

二、题解

class Solution {
   
public:
    int minSubarray(vector<int>& nums, int p) {
   
        int n = nums.size(),mod = 0;
        int res = INT_MAX;
        unordered_map<int,int> map;
        map[0] = -1;
        for(auto x:nums){
   
            mod = (mod + x) % p;
        }
        if(mod == 0) return 0;
        int cur = 0;
        for(int i = 0;i < n;i++){
   
            cur = (cur + nums[i]) % p;
            int t = (cur + p - mod) % p;
            if(map.find(t) != map.end()){
   
                res = min(res,i - map[t]);
            }
            map[cur] = i;
        }
        return res == n ? -1 : res;
    }
};

相关推荐

  1. LeetCode 150, 112, 130

    2024-01-13 08:14:07       23 阅读
  2. LeetCode1590. Make Sum Divisible by P

    2024-01-13 08:14:07       58 阅读
  3. Leetcode面试经典150

    2024-01-13 08:14:07       40 阅读
  4. LeetCode 150:逆波兰表达式

    2024-01-13 08:14:07       40 阅读
  5. leecode面试经典150

    2024-01-13 08:14:07       29 阅读
  6. 区间DP,LeetCode 1690. 石子游戏 VII

    2024-01-13 08:14:07       47 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-13 08:14:07       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-13 08:14:07       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-13 08:14:07       82 阅读
  4. Python语言-面向对象

    2024-01-13 08:14:07       91 阅读

热门阅读

  1. 【Leetcode】673.最长递增子序列的个数(Hard)

    2024-01-13 08:14:07       53 阅读
  2. python希尔排序

    2024-01-13 08:14:07       53 阅读
  3. 排序之堆排序

    2024-01-13 08:14:07       58 阅读
  4. Nacos_Linux上部署nacos

    2024-01-13 08:14:07       57 阅读
  5. Flink

    Flink

    2024-01-13 08:14:07      55 阅读
  6. 修改默认负载均衡策略(Ribbon)

    2024-01-13 08:14:07       58 阅读
  7. 使用spark将MongoDB数据导入hive

    2024-01-13 08:14:07       65 阅读
  8. CompletableFuture、ListenableFuture高级用列

    2024-01-13 08:14:07       42 阅读
  9. STM32 i2c从机模式中断处理参考

    2024-01-13 08:14:07       47 阅读