forked from yanglei-github/Leetcode_in_python3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1248_统计「优美子数组」.py
More file actions
69 lines (62 loc) · 1.81 KB
/
1248_统计「优美子数组」.py
File metadata and controls
69 lines (62 loc) · 1.81 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 13:52:29 2020
@author: leiya
"""
'''
0712
前缀和+滑动窗口
参考:930,992(based on 904)
'''
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
def atmost(nums,k):
start = 0
count = 0
odd_count = 0
for end in range(len(nums)):
if nums[end] % 2 != 0:
odd_count += 1
while odd_count > k:
if nums[start] % 2 != 0:
odd_count -= 1
start += 1
count += end-start+1
#注意return返回的位置,要在for循环外返回
return count
return atmost(nums,k) - atmost(nums,k-1)
#前缀和+差分+哈希表
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
#dict中存放到这个位置的奇数的个数
adict = {}
adict[0] = 1
#temp是奇数的个数
temp = 0
res = 0
for i in range(len(nums)):
if nums[i] % 2 == 1:
temp += 1
if temp - k in adict:
res += adict[temp-k]
if temp in adict:
adict[temp] += 1
else:
adict[temp] = 1
return res
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
odd_count = 0
adict = {}
adict[0] = 1
count = 0
for num in nums:
if num % 2 != 0:
odd_count += 1
if odd_count - k in adict:
count += adict[odd_count-k]
if odd_count not in adict:
adict[odd_count] = 1
else:
adict[odd_count] += 1
return count