Python程式:按排序順序查詢平方元素列表


假設我們有一個名為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
  • 當index >= 0時,執行:
    • 如果|nums[l]| > |nums[r]|,則
      • res[index] := nums[l] * nums[l]
      • l := l + 1
    • 否則,
      • res[index] := nums[r] * nums[r]
      • r := r - 1
    • index := index - 1
  • 返回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]

更新於:2021年10月14日

560 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告