力扣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;
      }
  };
相关推荐
ADDDDDD_Trouvaille1 小时前
2026.2.13——OJ75-77题
c++·算法
重生之后端学习1 小时前
230. 二叉搜索树中第 K 小的元素
java·数据结构·算法·深度优先
近津薪荼1 小时前
dfs专题7—— 全排列
c++·学习·算法·深度优先
你的冰西瓜1 小时前
C++ STL算法——非修改序列算法
开发语言·c++·算法·stl
闻缺陷则喜何志丹1 小时前
P12275 [蓝桥杯 2024 国 Python B] 工厂|普及+
c++·算法·蓝桥杯·洛谷
宝贝儿好1 小时前
【强化学习】第九章:基于Action-Critic框架的强化学习
人工智能·python·深度学习·算法·动态规划
laplace01231 小时前
KL 散度1
人工智能·算法·agent·qwen
星火开发设计1 小时前
类模板:实现通用数据结构的基础
java·开发语言·数据结构·c++·html·知识
EE工程师1 小时前
数据结构篇 - 顺序队列
数据结构·顺序队列
白中白121382 小时前
算法题-14
数据结构·算法·leetcode