力扣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;
      }
  };
相关推荐
Sam_Deep_Thinking4 小时前
学数据结构到底有什么用
数据结构
kobesdu4 小时前
人形机器人SLAM:技术挑战、算法综述与开源方案
算法·机器人·人形机器人
椰羊~王小美6 小时前
随机数概念及算法
算法
阿Y加油吧7 小时前
算法实战笔记:LeetCode 169 多数元素 & 75 颜色分类
笔记·算法·leetcode
不要秃头的小孩7 小时前
力扣刷题——509. 斐波那契数
python·算法·leetcode·动态规划
We་ct7 小时前
LeetCode 120. 三角形最小路径和:动态规划详解
前端·javascript·算法·leetcode·typescript·动态规划
py有趣8 小时前
力扣热门100题之和为K的子数组
数据结构·算法·leetcode
hipolymers8 小时前
C语言怎么样?难学吗?
c语言·数据结构·学习·算法·编程
CS创新实验室9 小时前
从“跑得动”到“跑得稳”:深度剖析数据结构究竟是理论点缀还是核心战力?
数据结构