刷题笔记day02-数组快慢指针
你的名字
977. 有序数组的平方
思路就是:
// 思路就是,可能有负数的情况,那么平方后的数,一定是首尾之间选择。
那么使用双指针的方法就可以实现这个问题。
// 那么只需要比较一波,选择最大的既可
func sortedSquares(nums []int) []int {
var (
length = len(nums)
i = 0
j = length - 1
k = length - 1
result = make([]int, length)
)
// 遍历
for i <= j {
if nums[i] * nums[i] < nums[j] * nums[j] {
result[k] = nums[j] * nums[j]
j--
} else {
result[k] = nums[i] * nums[i]
i++
}
k--
}
return result
}
977. 有序数组的平方
当出现大于 target 的时候,那么就是将慢指针往前移动,如果还大,就在判断子序列的长度和result的大小。
class Solution:
# 用python实现一下
# 主要还是使用滑动窗口的方法
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
subLength: int = 0
result: int = pow(10, 9)
sum: int = 0
i: int = 0
# 迭代
for j in range(len(nums)):
sum += nums[j]
# 滑动窗口的精髓,
while (sum >= target):
subLength = j - i + 1
result = subLength if subLength < result else result
# print(result)
# 窗口:前置向后移动一位
sum -= nums[i]
i += 1
return result if result != pow(10, 9) else 0
```
## 59. 螺旋矩阵 II
思路就是,上,右,下,左,范围:左闭右开的原则
````python
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
pad: int = 1
result: List[List[int]] = [[0]*n for i in range(n)]
# 计数
count: int = 1
rowLow: int = 0
rowHigh: int = n-1
colLow: int = 0
colHigh: int = n-1
i: int = 0
j: int = 0
while True:
# 上
# for
j = colLow
for j in range(colLow, colHigh+1):
result[rowLow][j] = count
count += 1
# print(result)
# 上面往里缩进
rowLow += 1
if rowLow > rowHigh:
break
# 右
for i in range(rowLow, rowHigh+1):
result[i][colHigh] = count
count += 1
# 右边往里缩进
colHigh -= 1
if colHigh < colLow:
break
# +++++
# 下
# j = colHigh
for j in range(colHigh, colLow-1, -1):
result[rowHigh][j] = count
count += 1
# 下面往上缩进
rowHigh -= 1
if rowHigh < rowLow:
break
# 左
# i = rowLow
for i in range(rowHigh, rowLow-1, -1):
result[i][colLow] = count
count += 1
# 左边往里缩进
colLow += 1
if colLow > colHigh:
break
return result
```