algorithm-base/animation-simulation/前缀和/leetcode1248寻找优美子数组.md

154 lines
5.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [1248. ](https://leetcode-cn.com/problems/count-number-of-nice-subarrays/)
****
> nums k
>
> k
>
>
** 1**
> nums = [1,1,2,1,1], k = 3
> 2
> 3 [1,1,2,1] [1,2,1,1]
** 2**
> nums = [2,4,6], k = 1
> 0
>
** 3**
> nums = [2,2,2,1,2,2,1,2,2,2], k = 2
> 16
**HashMap**
****
K k sum += x
![_20210114222339](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信截图_20210114222339.c0gwtdh8m94.png)
key 1 value nums[0],nums[0,1].
Java Code:
```java
class Solution {
public int numberOfSubarrays(int[] nums, int k) {
if (nums.length == 0) {
return 0;
}
HashMap<Integer,Integer> map = new HashMap<>();
//统计奇数个数,相当于我们的 presum
int oddnum = 0;
int count = 0;
map.put(0,1);
for (int x : nums) {
// 统计奇数个数
oddnum += x & 1;
// 发现存在,则 count增加
if (map.containsKey(oddnum - k)) {
count += map.get(oddnum - k);
}
//存入
map.put(oddnum,map.getOrDefault(oddnum,0)+1);
}
return count;
}
}
```
C++ Code:
```cpp
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
if (nums.size() == 0) {
return 0;
}
map <int, int> m;
//统计奇数个数,相当于我们的 presum
int oddnum = 0;
int count = 0;
m.insert({0,1});
for (int & x : nums) {
// 统计奇数个数
oddnum += x & 1;
// 发现存在,则 count增加
if (m.find(oddnum - k) != m.end()) {
count += m[oddnum - k];
}
//存入
if(m.find(oddnum) != m.end()) m[oddnum]++;
else m[oddnum] = 1;
}
return count;
}
};
```
HashMap HashMap key value
Java Code:
```java
class Solution {
public int numberOfSubarrays(int[] nums, int k) {
int len = nums.length;
int[] map = new int[len + 1];
map[0] = 1;
int oddnum = 0;
int count = 0;
for (int i = 0; i < len; ++i) {
//如果是奇数则加一偶数加0相当于没加
oddnum += nums[i] & 1;
if (oddnum - k >= 0) {
count += map[oddnum-k];
}
map[oddnum]++;
}
return count;
}
}
```
C++ Code:
```cpp
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int len = nums.size();
vector <int> map(len + 1, 0);
map[0] = 1;
int oddnum = 0;
int count = 0;
for (int i = 0; i < len; ++i) {
//如果是奇数则加一偶数加0相当于没加
oddnum += nums[i] & 1;
if (oddnum - k >= 0) {
count += map[oddnum-k];
}
map[oddnum]++;
}
return count;
}
};
```