zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    C#基础
    C#基础
    Sqlserver数据库备份和还原
    C#基础
    Python3学习笔记4
    Python3学习笔记3
    调用接口Post xml和json数据的通用方法
    Python3学习笔记2
    Python3学习笔记1
    常见的PHP函数代码性能对比
  • 原文地址:https://www.cnblogs.com/yawenw/p/12343490.html
Copyright © 2011-2022 走看看