Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหารายการกำลังสองเรียงลำดับใน Python

สมมติว่าเรามีรายการตัวเลขชื่อ nums เรียงจากน้อยไปมาก เราต้องยกกำลังสองสมาชิกและคืนค่าผลลัพธ์เรียงลำดับ

เช่น ถ้าอินพุตคือ nums = [-8, -3, 0, 5, 6] ผลลัพธ์จะเป็น [0, 9, 25, 36, 64]

ขั้นตอนการแก้ปัญหา

  1. n := ขนาดของ nums
  2. l := 0, r := n - 1, index := n - 1
  3. res := รายการขนาดเท่า nums เติม 0
  4. ในขณะที่ 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
  5. คืนค่า 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]