1248. Count Number of Nice Subarrays
Solution
將問題簡化成求subarrays sum值 = k的問題 560:
nums[i] = nums[i] % 2
public int numberOfSubarrays(int[] nums, int k) {
int ret = 0;
for(int i = 0; i < nums.length; i++){
nums[i] = nums[i]%2;
}
HashMap<Integer, Integer> map = new HashMap<>();
int count = 0;
for(int i = 0 ; i < nums.length; i++){
count += nums[i];
if(count == k){
ret++;
}
ret += map.getOrDefault((count-k),0);
map.compute(count, (ks, v)->{
if(v == null) return 1;
else return v+1;
});
}
return ret;
}
Last updated
Was this helpful?