用 Python 编写程序按排序顺序查找平方元素列表
pythonserver side programmingprogramming更新于 2026/1/3 14:04:17
假设我们有一个名为 nums 的数字列表,其中元素按升序排序,我们必须对元素求平方并按排序顺序返回结果。
因此,如果输入为 nums = [-8, -3, 0, 5, 6],则输出为 [0, 9, 25, 36, 64]
为了解决这个问题,我们将遵循以下步骤 −
- n := nums 的大小
- l := 0
- r := n - 1
- index := n - 1
- res := 大小与 nums 相同的列表并用 0 填充
- while index >= 0,do
- if |nums[l]| > |nums[r]|, then
- res[index] := nums[l] * nums[l]
- l := l + 1
- 否则,
- res[index] := nums[r] * nums[r]
- r := r - 1
- index := index - 1
- if |nums[l]| > |nums[r]|, then
- 返回 res
示例
让我们看看下面的实现以便更好地理解 −
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]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

