罗恩收到了几个按递增顺序排序的整数列表 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]
fwj
(fwj)
2021 年7 月 21 日 01:23
2
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]
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]
hua123
(测开19期学委-花小田)
2021 年7 月 21 日 03:25
6
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 个赞
dong
(冬冬冬)
2021 年7 月 22 日 06:58
8
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]
1 个赞