力扣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;
      }
  };
相关推荐
Darkwanderor1 天前
什么数据量适合用什么算法
c++·算法
zc.ovo1 天前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣1 天前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣1 天前
力扣热门100题之回文链表
算法·leetcode·链表
Kk.08021 天前
数据结构|链表 刷题
数据结构·链表
月落归舟1 天前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
清华都得不到的好学生1 天前
数据结构->1.稀疏数组,2.数组队列(没有取模),3.环形队列
java·开发语言·数据结构
SilentSlot1 天前
【数据结构】Hash
数据结构·算法·哈希算法
是娇娇公主~1 天前
Lambda表达式详解
数据结构·c++