力扣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;
      }
  };
相关推荐
无忧.芙桃17 分钟前
C++语言原理与实践(十):vector类的底层实现
开发语言·c++·算法
乐迪信息24 分钟前
AI防爆摄像机,监测港口船舶航行偏航隐患
大数据·人工智能·深度学习·算法·计算机视觉
0+1111 小时前
算法 --模拟
c++·算法·leetcode
青山是哪个青山1 小时前
LeetCode 300:最长递增子序列
算法
hetao17338371 小时前
2026-10-01~02 hetao1733837 的刷题记录
c++·算法
小虎牙^O^2 小时前
模糊数学综合评价:从模糊数学到建模评价类模型
人工智能·算法
随意起个昵称2 小时前
【单调队列优化DP】U301134 绿色通道
算法·动态规划
Nil2082 小时前
leetcode 739每日温度
算法·leetcode·职场和发展
lvwangshu2 小时前
势能分析(摊还分析)
数据结构·数学·算法
盘古开天16663 小时前
PPO算法代码实战(三):PyTorch从零实现PPO求解CartPole
人工智能·pytorch·算法