977.有序数组的平方
文章详解:暴力破解、双指针法
(1)暴力破解
func sortedSquares(nums []int) []int {
n := len(nums)
res := make([]int, n)
for i := 0; i < n; i++ {
res[i] = nums[i] * nums[i]
}
sort.Ints(res)
return res
}
(2)双指针法
逆序插入数组:正数的相对位置不变, 需要调整负数平方后的相对位置
func sortedSquares(nums []int) []int {
n := len(nums)
left, right, index := 0, n - 1, n - 1
res := make([]int, n)
for left <= right {
if nums[right] * nums[right] < nums[left] * nums[left] {
res[index] = nums[left] * nums[left]
left++
}else {
res[index] = nums[right] * nums[right]
right--
}
index--
}
return res
}
209.长度最小的子数组
文章详解:暴力破解、滑动窗口
(1)暴力破解:超时了!
func minSubArrayLen(target int, nums []int) int {
n := len(nums)
len := math.MaxInt
for i := 0; i < n; i++ {
sum := 0
for j := i; j < n; j++ {
sum += nums[j]
if sum >= target {
tmp := j - i + 1
len = min(len, tmp)
break
}
}
}
if len == math.MaxInt {
return 0
}else {
return len
}
}
(2)滑动窗口:右指针探索,左指针更新
func minSubArrayLen(target int, nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
left, right := 0, 0
len := math.MaxInt
sum := 0
for right < n{
sum += nums[right]
for sum >= target{
tmp := right - left + 1
len = min(len, tmp)
sum -= nums[left]
left++
}
right++
}
if len == math.MaxInt {
return 0
}else {
return len
}
}
59.螺旋矩阵II
文章详解
注意:确定边界条件;数组初始化;循环从start
开始
func generateMatrix(n int) [][]int {
loop := 0
start := 0
count := 1
res := make([][]int, n)
for i := 0; i < n; i++ {
res[i] = make([]int, n)
}
i , j := 0, 0
for loop < n / 2 {
for j = start; j < n - loop - 1; j++ {
res[start][j] = count
count++
}
for i = start; i < n - loop - 1; i++ {
res[i][j] = count
count++
}
for ; j > start; j-- {
res[i][j] = count
count++
}
for ; i > start; i-- {
res[i][j] = count
count++
}
start++
loop++
}
if n % 2 == 1 {
res[start][start] = count
}
return res
}
相关推荐:
54. 螺旋矩阵
LCR 146. 螺旋遍历二维数组
只需在螺旋矩阵II思路基础上,考虑m 或 n 为奇数
的情况
loop < min(m/2, n/2)
若m <= n && m % 2 == 1
,需增加一行(不能被loop消耗掉):从start列走到n-loop-1列
若m > n && n % 2 == 1
,需增加一列(不能被loop消耗掉):从start行走到m-loop-1行
func spiralOrder(matrix [][]int) []int {
m := len(matrix)
n := len(matrix[0])
if m == 0 || n == 0 {
return []int{}
}
start := 0
i, j, k := 0, 0, 0
loop := 0
res := make([]int, m*n)
for loop < min(m/2, n/2) {
for j = start; j < n-loop-1; j++ {
res[k] = matrix[start][j]
k++
}
for i = start; i < m-loop-1; i++ {
res[k] = matrix[i][j]
k++
}
for ; j > start; j-- {
res[k] = matrix[i][j]
k++
}
for ; i > start; i-- {
res[k] = matrix[i][j]
k++
}
start++
loop++
}
if m <= n && m % 2 == 1 {
for j := start; j < n-loop; j++ {
res[k] = matrix[start][j]
k++
}
}
if m > n && n % 2 == 1 {
for i := start; i < m-loop; i++ {
res[k] = matrix[i][start]
k++
}
}
return res
}
总结
都得先看解题思路才能想明白,希望能慢慢进步吧