LeetCode977.Squares of a Sorted Array
程序员文章站
2022-07-07 19:37:45
题目 "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 }
参考链接
下一篇: 【C语言】结构体变量定义、初始化、使用