The title

Given an array of integers A sorted in non-descending order, return A new array of the squares of each number, also sorted in non-descending order.

Example 1:

Input: [- 4-1,0,3,10]

Output:,1,9,16,100 [0]

Example 2:

Input: [7-3,2,3,11]

Output:,9,9,49,121 [4]

1

A has been sorted in non-decreasing order, that is, A is sorted in increasing order, requiring that the new array composed of the squares of each number be sorted in non-decreasing order, even if the new array is sorted incrementally.

We know that on the number line, the closer we get to 0, the smaller the squared value is, so we can find the first non-negative index, and then we can start from that index to the left and right, adding the smaller squared value to our new array, until both sides are out of range.

code

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
    }
}
Copy the code

2

A is an increasing array, assuming the leftmost is negative and the rightmost is positive. The final element of the new array takes the greater of the square of the two numbers, inserts it into the first position in the array, and then moves closer and closer to the center. Finally, print the new array.

code

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
	}
}
Copy the code