สมมติว่าเรามีรายการตัวเลข nums ต้องหาใหม่ลิสต์ที่แต่ละ index i เป็นผลคูณของทุกตัวในลิสต์เดิมยกเว้น index i ห้ามใช้การหาร
ตัวอย่าง: nums = [2, 3, 4, 5, 6] ผลลัพธ์ [360, 240, 180, 144, 120]
ขั้นตอนการแก้ปัญหา (Prefix & Suffix Product)
- ถ้า
len(nums) < 1คืนค่าnums l = len(nums), สร้างleftและrightขนาดlเติมNonetemp = 1, วนลูปiจาก 0 ถึงl-1:- ถ้า
i == 0:left[i] = temp - อื่นๆ:
temp *= nums[i-1],left[i] = temp
- ถ้า
temp = 1, วนลูปiจากl-1ถึง 0:- ถ้า
i == l-1:right[i] = temp - อื่นๆ:
temp *= nums[i+1],right[i] = temp
- ถ้า
- สำหรับทุก
i:left[i] *= right[i] - คืนค่า
left
ตัวอย่างโค้ด Python
class Solution:
def solve(self, nums):
if len(nums) < 1:
return nums
l = len(nums)
left = [None] * l
right = [None] * l
temp = 1
for i in range(len(nums)):
if i == 0:
left[i] = temp
else:
temp = temp * nums[i - 1]
left[i] = temp
temp = 1
for i in range(len(nums) - 1, -1, -1):
if i == len(nums) - 1:
right[i] = temp
else:
temp = temp * nums[i + 1]
right[i] = temp
for i in range(len(nums)):
left[i] = left[i] * right[i]
return left
ob = Solution()
nums = [2, 3, 4, 5, 6]
print(ob.solve(nums)) # Output: [360, 240, 180, 144, 120]
อินพุต / เอาต์พุต
Input: [2, 3, 4, 5, 6]
Output: [360, 240, 180, 144, 120]