209.长度最小的子数组(滑动窗口)
1. 滑动窗口的重点思考如何移动起始位置是实现滑动窗口问题的核心
2. 这道题目中使用一个变量去保存数组起始位置
3. 使用一个for循环去遍历整个数组并使用sum_去保存遍历过程中的值
4. 如果该值 >= target 我们需要进行子数组的更新知道找到最小的
5. subL的计算是要知道从窗口起始位置到窗口结束位置有多少个数字
- ex. 在3到6之中有几个数字? 6-3+1 = 4 因为3到6中有4个数字当做完减法我们需要+1
6. 通过设置一个inf数字跟我们subl不断判断知道获得最小的位置
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
# define a inf number to compare with our sub array later on
result = float('inf')
# let this number collect value inside the silde window
sum_ = 0
# array start position
j = 0
# iterate array
for i in range(len(nums)):
# add inside slide window value
sum_ += nums[i]
# if we our sum_ match the target value; can't use if,since we need always fin
while sum_ >= target:
# creat subL to store temp window size
subL = i - j + 1 # the reason why we need add one is, between 3 to 6 6-3+1 = 4 there are four number
# compare with our result to find min
result = min(result,subL)
# sum_ value should update, we need delete nums[j] element,since we update new widonw position
sum_ = sum_ - nums[j]
# move j we need to slide our window
j += 1
# return answer if we got min size array, otherwise 0
return result if result != float('inf') else 0
59. 螺旋矩阵 II
- 初始化一个nxn的矩阵
- 初始化startx starty变量
- 循环多少圈是跟n//2挂钩的,从第1圈开始,每循环一圈offset值要+1
- 螺旋数组的核心关键在于区间以及顺序
- 使用左闭右开 [左区间,右区间)
- 从左到右
- 从上到下
- 从右到左
- 从下到上
- 最后判断一下n是否能整除2,如果不能说明是奇数,矩阵中心需要填充值
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
# create nxn array
matrix = [[0] * n for _ in range(n)]
# element value
count = 1
# x and y position
startx = 0
starty = 0
# record how many cycle
loop = n//2
mid = n//2 # if n is odd number, we should find the center value
# start loop; everytime we start loop we should incraest our offset
for offset in range(1,loop+1):
# left to right
for i in range(starty,n-offset):
matrix[startx][i] = count
count += 1
# top to bottom
for i in range(startx,n-offset):
matrix[i][n-offset] = count
count += 1
# right to left; don't forgot step should be -1, we are decrease
for i in range(n-offset,starty,-1):
matrix[n-offset][i] = count
count += 1
# bottom to top; don't forgot step should be -1, we are decrease
for i in range(n-offset,startx,-1):
matrix[i][starty] = count
count += 1
# finished first loop of matrix, increase startx and starty value
startx += 1
starty += 1
# check if the n is odd number
if n%2 != 0:
# we should fill out the center
matrix[mid][mid] = count
return matrix
总结
1. 滑动窗口要清楚窗口的起始位置以及如何判断窗口是否应该滑动
2. 螺旋数组循环的区间边界和每一条边界处理规则是关键,记好口诀;
从左到右,从上到下,从右到左,从下到上;遇到奇数记得填充