Description
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.
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
题目链接:https://leetcode.com/problems/squares-of-a-sorted-array/
Difficulty: easy
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.
分析
- 找到最小点(距离0最近的点)index;
- 设置两个游标i,j从index向左右移动;
- 移动判断移动i或j,得到有序数组的平方。
参考代码
class Solution:
def sortedSquares(self, A):
    target=abs(A[0])
    index=0
    for i in range(len(A)):
        if(abs(A[i])<=target):
            index=i
            target=abs(A[i])
        else:
            break
    i=index
    j=index+1
    li=[]
    while(i >= 0 and j < len(A)):
        if(abs(A[i])<abs(A[j])):
            li.append(A[i]**2)
            i-=1
        else:
            li.append(A[j]**2)
            j+=1
    while(i>=0):
        li.append(A[i]**2)
        i-=1
    while(j<len(A)):
        li.append(A[j]**2)
        j+=1
    return li