leetcode977 Squares of a Sorted Array

我只是一个虾纸丫 提交于 2020-02-21 22:54:10
 1 """
 2 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.
 3 Example 1:
 4 Input: [-4,-1,0,3,10]
 5 Output: [0,1,9,16,100]
 6 Example 2:
 7 Input: [-7,-3,2,3,11]
 8 Output: [4,9,9,49,121]
 9 """
10 """
11 注意观察序列,绝对值大的都在两端
12 所以可以用头尾两个指针进行遍历
13 """
14 class Solution1:
15     def sortedSquares(self, A):
16         res = [0]*len(A)
17         i, j = 0, len(A)-1
18         for k in range(j, -1, -1): #!!!注意这里的写法第二个为-1,区间是[len(A)-1, 0]
19             if abs(A[i]) > abs(A[j]):
20                 res[k] = A[i]**2
21                 i += 1
22             else:
23                 res[k] = A[j]**2
24                 j -= 1
25         return res
26 """
27 解法二:sorted函数
28 """
29 class Solution2:
30     def sortedSquares(self, A):
31         return sorted(i**2 for i in A)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!