【每日一题0721】 有序列表的平方

:woman_mage:罗恩收到了几个按递增顺序排序的整数列表 nums ,任务是返回每个数字的平方值组成的新列表,要求也按 递增顺序 排序。让我们编写一个python函数帮帮他吧~

示例:
输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
说明:平方后,数组变为 [16,1,0,9,100];排序后,数组变为 [0,1,9,16,100]

题目难度:简单
题目来源:力扣 977. 有序数组的平方

def sorted_squares(nums:list) -> list: 
    pass

assert sorted_squares([-4,-1,0,3,10])  == [0,1,9,16,100]
assert sorted_squares([-7,-3,2,3,11])  == [4,9,9,49,121]
def sorted_squares(nums:list):
    res=[]
    for i in nums:
        res.append(i**2)
    res.sort()
    return res

assert sorted_squares([-4,-1,0,3,10])  == [0,1,9,16,100]
assert sorted_squares([-7,-3,2,3,11])  == [4,9,9,49,121]

@fwj :clap: :clap: :clap: 少侠功力深厚,快如闪电~

只会做这种简单程度的题了 :sweat_smile:

def sorted_squares(nums:list) -> list:
    li = []
    for i in nums:
        i = i**2
        li.append(i)
    li.sort()
    return li

assert sorted_squares([-4,-1,0,3,10])  == [0,1,9,16,100]
assert sorted_squares([-7,-3,2,3,11])  == [4,9,9,49,121]
def  sorted_squares(nums:list) -> list:
     return  sorted(map(lambda  x:x**2,nums))

assert sorted_squares([-4,-1,0,3,10])  == [0,1,9,16,100]
assert sorted_squares([-7,-3,2,3,11])  == [4,9,9,49,121]
def sorted_squares(nums: list) -> list:
    res = [abs(i) ** 2 for i in nums]
    return sorted(res)


assert sorted_squares([-4, -1, 0, 3, 10]) == [0, 1, 9, 16, 100]
assert sorted_squares([-7, -3, 2, 3, 11]) == [4, 9, 9, 49, 121]
1 个赞
def sorted_squares(nums: list) -> list:
    return sorted([i**2 for i in nums])

assert sorted_squares([-4,-1,0,3,10])  == [0,1,9,16,100]
assert sorted_squares([-7,-3,2,3,11])  == [4,9,9,49,121]

思路1:

def sorted_squares(nums:list) -> list: 
    return sorted([x*x for x in nums])

assert sorted_squares([-4,-1,0,3,10])  == [0,1,9,16,100]
assert sorted_squares([-7,-3,2,3,11])  == [4,9,9,49,121]

思路2:

def sorted_squares(nums:list) -> list: 
    return sorted(list(map(lambda x:x**2, nums)))

assert sorted_squares([-4,-1,0,3,10])  == [0,1,9,16,100]
assert sorted_squares([-7,-3,2,3,11])  == [4,9,9,49,121]

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

1 个赞