Skip to content

Commit ffca497

Browse files
committed
solution 977 by go
1 parent 04c1c11 commit ffca497

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

go/977-solution.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
/**
8+
* LC#977:Squares of a Sorted Array
9+
* Link:https://leetcode-cn.com/problems/squares-of-a-sorted-array/
10+
* Method 1:After calculating the square of the array, sort it
11+
* Method 2:Double Pointer
12+
* Remark:Method 2 双指针的精髓在于利用的数组已有的顺序
13+
*/
14+
func sortedSquares(nums []int) []int {
15+
n := len(nums)
16+
ans := make([]int, n)
17+
i, j, pos := 0, n-1, n-1
18+
for i <= j {
19+
sis := nums[i] * nums[i]
20+
eis := nums[j] * nums[j]
21+
if sis > eis {
22+
ans[pos] = sis
23+
i++
24+
} else {
25+
ans[pos] = eis
26+
j--
27+
}
28+
pos--
29+
}
30+
return ans
31+
}
32+
33+
func main() {
34+
intList := []int{-4, -1, 0, 3, 10}
35+
res := sortedSquares(intList)
36+
fmt.Println(res)
37+
}

0 commit comments

Comments
 (0)