在Python中按排序顺序查找平方元素列表的程序
假设我们有一个名为nums的数字列表,其中元素按升序排序,我们必须对元素进行平方并按排序顺序返回结果。
因此,如果输入类似于nums=[-8,-3,0,5,6],那么输出将是[0,9,25,36,64]
示例
让我们看看以下实现以获得更好的理解-
def solve(nums):
n = len(nums)
l = 0
r = n - 1
index = n - 1
res = [0 for i in range(len(nums))]
while index >= 0:
if abs(nums[l]) > abs(nums[r]):
res[index] = nums[l] * nums[l]
l += 1
else:
res[index] = nums[r] * nums[r]
r -= 1
index -= 1
return res
nums = [-8, -3, 0, 5, 6]
print(solve(nums))输入
[-8, -3, 0, 5, 6]输出结果
[0, 9, 25, 36, 64]
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短