力扣1248.统计优美子数组

力扣1248.统计优美子数组

  • 同930.

哈希表法

  • 求前缀和

cpp 复制代码
  class Solution {
  public:
      int numberOfSubarrays(vector<int>& nums, int k) {
          int n = nums.size();
          unordered_map<int,int> cnt;
          int res=0,sum=0;
          for(int i=0,j=0;i<n;i++)
          {
              cnt[sum] ++;
              if(nums[i] & 1) sum ++;
              res += cnt[sum - k];
          }
          return res;
      }
  };

多指针法

  • 用两个左指针卡左边可取的区间范围

cpp 复制代码
  class Solution {
  public:
      int numberOfSubarrays(vector<int>& nums, int k) {
          int n = nums.size();
          int res=0,s1=0,s2=0;
          for(int i=0,j1=0,j2=0;i<n;i++)
          {
              int x = (nums[i] & 1);
              s1 += x;
              s2 += x;
              //s1 --> s1 < k
              while(j1 <= i && s1 >= k) s1 -= (nums[j1++] & 1);
              //s2 --> s2 == k
              while(j2 <= i && s2 > k) s2 -= (nums[j2++] & 1);
              //此时j1的位置比j2靠右
              res += j1 - j2;
          }
          return res;
      }
  };
相关推荐
vibecoding日记14 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr213816 小时前
Verilog参数化游程编码RLE模块
算法
望易16 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络20 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩2 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹2 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术2 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望2 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法