-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
34 lines (30 loc) · 919 Bytes
/
Solution.cs
File metadata and controls
34 lines (30 loc) · 919 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
namespace LeetCode.Medium.Problem1248{
//1248. Count Number of Nice Subarrays
//https://leetcode.com/problems/count-number-of-nice-subarrays/
/*
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
*/
public class Solution {
public int NumberOfSubarrays(int[] nums, int k) {
int ans = 0;
int counter = 0;
Dictionary<int,int> dic = new Dictionary<int,int>();
dic.Add(0,1);
for (int right = 0; right < nums.Length; right++)
{
if (nums[right] % 2 == 1)
counter++;
if (dic.ContainsKey(counter - k)) {
ans += dic[counter - k];
}
if (dic.ContainsKey(counter)) {
dic[counter]++;
} else {
dic.Add(counter, 1);
}
}
return ans;
}
}
}