力扣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;
      }
  };
相关推荐
小许学java3 小时前
数据结构-ArrayList与顺序表
java·数据结构·顺序表·arraylist·线性表
格林威5 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
程序员莫小特7 小时前
老题新解|大整数加法
数据结构·c++·算法
小刘max8 小时前
深入理解队列(Queue):从原理到实践的完整指南
数据结构
过往入尘土8 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.8 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!8 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
蒙奇D索大8 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
洲覆8 小时前
C++ 模板、泛型与 auto 关键字
开发语言·数据结构·c++
MoRanzhi12038 小时前
15. Pandas 综合实战案例(零售数据分析)
数据结构·python·数据挖掘·数据分析·pandas·matplotlib·零售