leetcode977 Squares of a Sorted Array

 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)

猜你喜欢

转载自www.cnblogs.com/yawenw/p/12343490.html
今日推荐