力扣1590.使数组和能被P整除

力扣1590.使数组和能被P整除

  • 同余

    • 转化为求一段区间和余p为x
    • i - j = x
      • j = i - x
cpp 复制代码
  class Solution {
  public:
      int minSubarray(vector<int>& nums, int p) {
          int x = accumulate(nums.begin(),nums.end(),0LL) % p;
          if(x == 0) return 0;
          int n = nums.size(),ans = n,s = 0;
          unordered_map<int,int> last{{s,-1}};
          for(int i=0;i<n;i++)
          {
              s = (s + nums[i]) % p;
              last[s] = i;
              auto it = last.find((s - x + p) % p);
              if(it != last.end())
                  ans = min(ans,i - it->second);
          }
          return ans < n ? ans : -1;
      }
  };
相关推荐
himobrinehacken5 分钟前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
INGNIGHT37 分钟前
815 · 课程表IV(dfs)
算法·深度优先
文丑颜不良啊1 小时前
LeetCode1~50题目解析
leetcode
Pniubi1 小时前
力扣146.LRU缓存机制
算法·leetcode·缓存
云上工程笔记1 小时前
2026年7B到67B模型训练与推理GPU配置评测:LoRA、量化与全量微调对比
人工智能·算法·机器学习
softlgh1 小时前
鼾声识别:嵌入式离线鼾声检测 SDK 与睡眠健康数据
算法·智能家居·智能音箱·鼾声识别·智能枕头·打呼噜
了了1 小时前
图搜索基础学习笔记
算法
淡海水2 小时前
05-02-源码-Boehm GC标记阶段
算法·unity·c#·游戏引擎·gc
Code_Solitude2 小时前
传智杯备赛代码整理(前4题)
数据结构·算法
Jasmine_llq3 小时前
《P8816 [CSP-J 2022] 上升点列》
数据结构·算法·贪心·排序·二维动态规划 dp·类背包状态转移