LeetCode977.Squares of a Sorted Array

本文提供LeetCode上编号为977的题目“有序数组的平方”的解决方案。该题要求对给定的非递减有序整数数组,返回每个元素的平方,并保持非递减顺序。示例输入[-4,-1,0,3,10],正确输出[0,1,9,16,100]。文章详细解析了算法思路并附带Go语言实现代码。

题目

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

转载于:https://www.cnblogs.com/peerless1024/p/10836631.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值