學習資料:https://programmercarl.com/陣列總結篇.html#陣列的經典題目
移動窗格,首尾指標根據條件變化
模擬行為,迴圈不變數(左閉右閉或左閉右開)整個過程保持一致
學習記錄:
209.長度最小的子陣列(用while使得尾指標遍歷全部;用while實現,當[首:尾]之和>目標值,才移動首指標;為了求最小長度,先設定最小長度為正無窮float('inf'))
點選檢視程式碼
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
begin=0
end=0
sum=0
min_len=float('inf') #設定為無窮大,方便找到最小值
while end < len(nums):
sum += nums[end]
while sum >= target:
sum -= nums[begin]
sub_l=end-begin+1
min_len = min(sub_l, min_len)
begin += 1
end += 1
if min_len != float('inf'):
return min_len
else:
return 0
59.螺旋矩陣(邊界值很多,有初始橫縱指標、左閉右開需要從n剪掉的offset、從1開始計數的count;當奇數階矩陣,中間多出來的1項單獨設定;螺旋轉的圈數為n//2)
點選檢視程式碼
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
start_x = 0
start_y = 0
nums = [[0]*n for _ in range(n)]
cycle, mid = n//2, n//2
offset=1
count=1
for c in range(cycle):
for j in range(start_y, n-offset):
nums[start_x][j]=count
count += 1
for i in range(start_x, n-offset):
nums[i][n-offset]=count
count += 1
for j in range(n-offset, start_y, -1):
nums[n-offset][j]=count
count += 1
for i in range(n-offset, start_x, -1):
nums[i][start_y] = count
count += 1
start_x += 1
start_y += 1
offset += 1
if n%2 != 0:
nums[mid][mid]=count
return nums
PS:
螺旋矩陣好繞啊,被9個數字給繞麻了
今天陰天,好冷,終於要放假了