LeetCode977.Squares of a Sorted Array
程序员文章站
2022-04-19 12:40:58
题目 "977. Squares of a Sorted Array" Given an array of integers A sorted in non decreasing order, return an array of the squares of each number, also i ......
题目
977. squares of a sorted array
given an array of integers a sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
example 1:
input: [-4,-1,0,3,10] output: [0,1,9,16,100]
example 2:
input: [-7,-3,2,3,11] output: [4,9,9,49,121]
note:
- 1 <= a.length <= 10000
- -10000 <= a[i] <= 10000
- a is sorted in non-decreasing order.
答案
func sortedsquares(a []int) []int { size := len(a) res := make([]int, size) for l, r, i := 0, size-1, size-1; l <= r; i-- { if a[l]+a[r] < 0 { res[i] = a[l] * a[l] l++ } else { res[i] = a[r] * a[r] r-- } } return res }
参考链接
上一篇: 顺丰原生地址库封装
推荐阅读