文章详解:暴力破解、双指针法
(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
}
文章详解:暴力破解、滑动窗口
(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
}
}
文章详解
注意:确定边界条件;数组初始化
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. 螺旋遍历二维数组
都得先看解题思路才能想明白,希望能慢慢进步吧