力扣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;
      }
  };
相关推荐
课堂剪切板19 分钟前
ch07 题解
算法·深度优先
R_AirMan37 分钟前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
科大饭桶2 小时前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
小高Baby@2 小时前
map数据结构在Golang中是无序的,并且键值对的查找效率较高的原因
数据结构
北风toto2 小时前
python学习DataFrame数据结构
数据结构·python·学习
我爱C编程4 小时前
基于Qlearning强化学习的1DoF机械臂运动控制系统matlab仿真
算法
chao_7894 小时前
CSS表达式——下篇【selenium】
css·python·selenium·算法
chao_7894 小时前
Selenium 自动化实战技巧【selenium】
自动化测试·selenium·算法·自动化
YuTaoShao4 小时前
【LeetCode 热题 100】24. 两两交换链表中的节点——(解法一)迭代+哨兵
java·算法·leetcode·链表
怀旧,4 小时前
【数据结构】8. 二叉树
c语言·数据结构·算法