977. squares of a sorted array
例子:-4,-1,0,3,10
又是一个双指针,发现我们的array最大数只能在两头,故用双指针放置两头比较谁更大
学习了下python如何创建一个vector
res = [float('inf')] * len(nums) # 需要提前定义列表,存放结果
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left = 0
right = len(nums)-1
res = [float('inf')]*len(nums)
i = len(nums)-1
while(left<=right):
if nums[left]*nums[left]>nums[right]*nums[right]:
res[i]=nums[left]*nums[left]
left+=1
else:
res[i]=nums[right]*nums[right]
right-=1
i-=1
return res
209 minimum size subarray sum
还是双指针(滑动窗口)。
因为题目要求是找minimal length of a subarray whose sum is greater than or equal to target(而不是sum exactly equal to target),所以我们的
trick在于第一个while逐一遍历right pointer,然后据此移动left pointer(left pointer 只能向后移动不需要重新从index=0开始),这样就不用两层循环O(n^2)了。
其实这里的双指针是对暴力解法的一种简化
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
left=0 #the left pointer
right=0 #the right pointer
s=0
length = float('inf')
while(right<len(nums)):
s += nums[right]
while (s>=target):
l = right-left+1
s -= nums[left]
length = min(length,l)
left+=1
right+=1
if length!=float('inf'):
return length
else:
return 0
59. spiral matrix 2
要点:
1.注意每条边统一左闭右开
2.n为奇数和偶数时不同写法
codes for generate a n by n matrix
nums = [[0] * n for _ in range(n)]
可以再练习写一遍
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
startx=0 #row index
starty=0 #column index
count=1
nums = [[0] * n for _ in range(n)]
rounds = n//2
mid = n//2
for offset in range(1,rounds+1):
for i in range(starty,n-offset):
nums[startx][i]=count
count+=1
for i in range(startx,n-offset):
nums[i][n-offset]=count
count+=1
for i in range(n-offset,starty,-1):
nums[n-offset][i]=count
count+=1
for i in range(n-offset,startx,-1):
nums[i][starty]=count
count+=1
startx+=1
starty+=1
if n%2 ==1:
nums[mid][mid]=count
return nums