思路:将两个指针分别指向初始值和终值,从两端向中间步进,把较大的输出到result数组中
暴力解法:
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums[i] = nums[i] * nums[i]
results = sorted(nums)#sorted函数直接用
return results
总结:可以直接用sorted函数
双指针解法:
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n, k = len(nums), len(nums) - 1
result = [0] * n
i, j= 0, k
while i <= j:
if nums[i] * nums[i] < nums[j] * nums[j]:
result[k] = nums[j] * nums[j]
k = k - 1
j = j - 1
else:
result[k] = nums[i] * nums[i]
k = k - 1
i = i + 1
return result
思路:用双指针法
滑动窗口解法:
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
sum = 0
i, result = 0, len(nums) + 1
for j in range(len(nums)):
sum = sum + nums[j]
while sum >= target:
subL = j - i + 1
result = min(subL, result)
sum = sum - nums[i]
i = i + 1
if result == len(nums) + 1:#如果结果从来没有更新过,说明没有符合要求的target,通过这个判断条件来输出0
return 0
return result
总结:在最后的判断条件中出错了,没有考虑不存在的情况,如果不存在,说明整个数组的和都小于target,也就是说从来没有进入过while循环,result依然是初始值,通过这个条件可以确定不存在情况
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
count = 1
loop = n // 2
startx, starty = 0, 0
nums = [[ 0 for i in range(n)] for j in range(n)]
for offset in range(1, loop + 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[loop][loop] = count
return nums
总结:通过nums = [[0] * n]*n初始化二维数组的方法,会使得改变每行的一个元素时,其他行的同一列元素也会改变