LeeCode 977. 有序数组的平方

310 阅读1分钟

题目

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

  示例 1:

输入:[-4,-1,0,3,10]

输出:[0,1,9,16,100]

示例 2:

输入:[-7,-3,2,3,11]

输出:[4,9,9,49,121]

解题思路 1

A 已按非递减顺序排序,即为 A是按照递增顺序排序,要求每个数字平方组成的新数组按照非递减的顺序排序,即为新数组也要递增排序。

我们知道,在数轴上,离 0 越近,平方后的值就越小,我们可以先找到第一个非负数的索引,然后从这个索引向左向右开始遍历比较,将平方后比较小的值添加到我们的新数组中,知道两边都超出数组范围结束。

代码

class Solution {
    func sortedSquares(_ A: [Int]) -> [Int] {
        var startIndex = 0
        for (index, value) in A.enumerated() {
            if value >= 0 {
                startIndex = index
                break
            }
        }
        var leftIndex = startIndex-1
        var result = [Int]()
        while leftIndex >= 0 || startIndex < A.count {
            var temp = -1
            if leftIndex >= 0 {
                temp = A[leftIndex]*A[leftIndex]
            }
            var temp1 = -1
            if startIndex < A.count {
                temp1 = A[startIndex]*A[startIndex]
            }
            if temp == -1 {
                startIndex += 1
                result.append(temp1)
                continue
            }
            if temp1 == -1 {
                leftIndex -= 1
                result.append(temp)
                continue
            }
            if temp < temp1 {
                leftIndex -= 1
                result.append(temp)
            } else {
                startIndex += 1
                result.append(temp1)
            }
        }
        return result
    }
}

解题思路 2

A 为递增数组,假设最左边为负,最右边为正数。那么新数组的最后元素就在这两个数的平方中取较大值,插入到数组的第一个位置,然后逐渐向中间靠拢。最后输出新数组即可。

代码

class Solution {
    func sortedSquares(_ A: [Int]) -> [Int] {
        var result = [Int]()
        var left = 0
        var right = A.count-1
        while left <= right {
            if A[left]*A[left] > A[right]*A[right] {
                result.insert(A[left]*A[left], at: 0)
                left += 1
            } else {
                result.insert(A[right]*A[right], at: 0)
                right -= 1
            }
        }
        return result
	}
}