1590. 使数组和能被 P 整除

1590. 使数组和能被 P 整除


题目链接:1590. 使数组和能被 P 整除

代码如下:

cpp 复制代码
class Solution {
public:
	int minSubarray(vector<int>& nums, int p) {
		int x = 0;
		for (auto num : nums) {
			x = (x + num) % p;
		}
		if (x == 0) {
			return 0;
		}
		unordered_map<int, int> index;
		int y = 0, res = nums.size();
		for (int i = 0;i < nums.size();i++) {
			index[y] = i;	// f[i] mod p = y, 因此哈希表记录 y 对应的下标为 i
			y = (y + nums[i]) % p;
			if (index.count((y - x + p) % p) > 0) {
				res = min(res, i - index[(y - x + p) % p] + 1);
			}
		}
		return res == nums.size() ? -1 : res;
	}
};
相关推荐
Lazionr25 分钟前
多态:从多种形态到运行时绑定
开发语言·c++
别动我齐刘海36 分钟前
ROS2 Jazzy + C++ 实战路线——ros2_control
c++·人工智能·python·opencv·机器学习·机器人·github
All for pursuit.1 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
码匠许师傅1 小时前
【C++三方组件】glog:Google 出品的 C++ 日志库
c++
Lazionr1 小时前
二叉搜索树:从树形结构到高效查找
开发语言·c++
此生决int1 小时前
深入理解C++系列(21)——异常
开发语言·c++
曼巴UE51 小时前
UE5 客户端 需要的网络同步概念总结(3 )-事件同步 RPC 以及三种调用方式
网络·c++·网络协议·学习·rpc·ue5
All for pursuit.2 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
01二进制代码漫游日记2 小时前
C++之类和对象(上)02
c++
渡我白衣2 小时前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe