mirror of
https://gitlab.com/game-loader/hugo.git
synced 2025-04-20 14:02:07 +08:00
add leetcode content
This commit is contained in:
parent
943c8ec9d4
commit
a5552c4d12
@ -265,3 +265,79 @@ func maximumOddBinaryNumber(s string) string {
|
|||||||
### 总结
|
### 总结
|
||||||
|
|
||||||
在处理字符串的时候像中间某个位置插入字符也要使用双引号, 如插入字符0要用`+"0"`而不是`+'0'`, 此外在截取切片的时候go的切片是左闭右开的. 如[0:3]截取的是0,1,2三个数
|
在处理字符串的时候像中间某个位置插入字符也要使用双引号, 如插入字符0要用`+"0"`而不是`+'0'`, 此外在截取切片的时候go的切片是左闭右开的. 如[0:3]截取的是0,1,2三个数
|
||||||
|
|
||||||
|
## day5 2024-03-02
|
||||||
|
|
||||||
|
### 977. Squares of a Sorted Array
|
||||||
|
|
||||||
|
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
|
||||||
|
Input: nums = [-4,-1,0,3,10]
|
||||||
|
Output: [0,1,9,16,100]
|
||||||
|
Explanation: After squaring, the array becomes [16,1,0,9,100].
|
||||||
|
After sorting, it becomes [0,1,9,16,100].
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
|
||||||
|
Input: nums = [-7,-3,2,3,11]
|
||||||
|
Output: [4,9,9,49,121]
|
||||||
|
|
||||||
|
### 题解
|
||||||
|
|
||||||
|
考虑原数组已经按照非递减排序的情况下, 找到数组中正负交界处元素, 即数组中第一个正数, 以该位置作为起始位置, 使用双指针法, 分别向前和向后遍历数组, 遍历时不断比较两个指针指向的数字的绝对值大小, 将绝对值小的数字平方后追加到结果数组的尾部, 遍历完成即可完成平方值排序. 这样只需要遍历一遍数组即可完成排序.
|
||||||
|
|
||||||
|
### 代码
|
||||||
|
|
||||||
|
```go
|
||||||
|
func sortedSquares(nums []int) []int {
|
||||||
|
index := 0
|
||||||
|
value := nums[0]
|
||||||
|
var result []int
|
||||||
|
for index, value = range nums{
|
||||||
|
if(value >= 0){
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
backward := index - 1
|
||||||
|
forward := index
|
||||||
|
if index != 0{
|
||||||
|
for _,_ = range nums{
|
||||||
|
if backward<0{
|
||||||
|
result = append(result, nums[forward]*nums[forward])
|
||||||
|
forward++
|
||||||
|
} else if forward>= len(nums){
|
||||||
|
result = append(result, nums[backward] * nums[backward])
|
||||||
|
backward--
|
||||||
|
} else{
|
||||||
|
if(abs(nums[forward]) < abs(nums[backward])){
|
||||||
|
result = append(result, nums[forward]*nums[forward])
|
||||||
|
forward++
|
||||||
|
} else{
|
||||||
|
result = append(result, nums[backward] * nums[backward])
|
||||||
|
backward--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}else{
|
||||||
|
for _,_ = range nums{
|
||||||
|
result = append(result, nums[forward]*nums[forward])
|
||||||
|
forward++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func abs(val int) int {
|
||||||
|
if(val < 0){
|
||||||
|
return -val
|
||||||
|
}else{
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 总结
|
||||||
|
|
||||||
|
注意一个go的语法问题, 如果在for range循环中两个变量都使用匿名变量, 则应该使用赋值运算符而不是创建并赋值运算符, 即`for _,_ = range slice` 而不是`for _,_ := range slice`. 这很可能是因为匿名变量默认为已经创建好的变量, 不需要再创建匿名变量本身了.
|
||||||
|
Loading…
Reference in New Issue
Block a user