欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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
}

参考链接

977. squares of a sorted array