文章目录
-
- 一、题目
- 二、题解
一、题目
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 1 1
二、题解
class Solution {
public:
int minSubarray(vectorint>& nums, int p) {
int n = nums.size(),mod = 0;
int res = INT_MAX;
unordered_mapint,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;
}
};
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
相关推荐: 二进制安装Kubernetes(k8s)v1.29.2
二进制安装Kubernetes(k8s)v1.29.2 https://github.com/cby-chen/Kubernetes 开源不易,帮忙点个star,谢谢了 介绍 kubernetes(k8s)二进制高可用安装部署,支持IPv4+IPv6双栈。 我…