1. Substring
1.1 Question 560 - The subarray whose sum is k
Given an integer array nums
and an integer k
, count and return the number of consecutive subarrays in the array whose sum is k
.
Example 1:
Input: nums = [1,1,1], k = 2 Output: 2
At first, I wanted to use a sliding window, but during the operation, I encountered many examples that were difficult to handle and it was difficult to handle. I looked directly at the analysis and decided to use ij range traversal, but the result was a timeout.
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
n = len(nums)
cur_arr = []
result = 0
cur_sum = -100000000
last_sum = 0
sum_nums = 0
for i in range(n):
sum_nums += nums[i]
cur_sum = sum_nums
sum_temp = sum_nums
for i in range(n):
if i != 0:
sum_temp -= nums[i-1]
cur_sum = sum_temp
for j in reversed(range(i,n)):
if cur_sum == k:
result += 1
cur_sum -= nums[j]
return result
After reading the analysis, it's really hard to think about it.
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
n = len(nums)
cur_arr = []
result = 0
last_sum = 0
sum_nums = 0
# 必须初始化为0:1,不然sum_nums-k=0时,result就不能加一了
dic = {0:1}
for i in range(n):
# 求前缀和
sum_nums += nums[i]
# 如果字典中存在sum_nums-k,则说明sum_nums对应的i与sum_nums-k对应的i之间和为k
# 如果sum_nums-k的键值不唯一,就表示有多个i的前缀和为sum_nums-k
# 这时result就加上键值
result += dic.get(sum_nums-k, 0)
# 最后把该i的前缀和加入到字典中,若已存在则键值加一
dic[sum_nums] = dic.get(sum_nums, 0) + 1
print(dic, result)
return result
1.2 Question 239 - Sliding window maximum
You are given an array of integers nums
with a k
sliding window of size moving from the far left of the array to the far right of the array. k
You can only see the numbers within the sliding window . The sliding window only moves to the right one bit at a time.
Returns the maximum value in a sliding window .
Thoughts: The idea seems to be quite simple, just write the sliding window directly, but it times out.
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
result = []
cur_win = []
for i in range(k-1):
cur_win.append(nums[i])
for i in range(len(nums)-k+1):
cur_max = -100000
cur_win.append(nums[i+k-1])
for j in range(k):
if cur_max < cur_win[j]:
cur_max = cur_win[j]
# cur_max = max(cur_win)
result.append(cur_max)
cur_win = cur_win[1:]
return result
The parsing is a bit complicated.