สมมติว่าเรามีอาร์เรย์เก็บตัวเลขบางจำนวน มีค่าที่ไม่ใช่ศูนย์และค่าศูนย์ เราต้องส่งศูนย์ทั้งหมดไปทางขวาโดยไม่เปลี่ยนลำดับสัมพัทธ์ของตัวเลขอื่นๆ เช่นถ้าอาร์เรย์เป็น [0, 1, 5, 0, 3, 8, 0, 0, 9] อาร์เรย์สุดท้ายจะเป็น [1, 5, 3, 8, 9, 0, 0, 0, 0]
วิธีการแก้ปัญหา
- สมมติ index = 0
- สำหรับ i = 0 ถึงความยาวของ A:
- ถ้า A[i] != 0:
- A[index] := A[i]
- index := index + 1
- ถ้า A[i] != 0:
- สำหรับ i = index ถึงความยาวของ A:
- A[i] = 0
ตัวอย่างโค้ด
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
insert_index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[insert_index] = nums[i]
insert_index += 1
for i in range(insert_index, len(nums)):
nums[i] = 0
nums = [0,1,5,0,3,8,0,0,9]
ob1 = Solution()
ob1.moveZeroes(nums)
print(nums)
อินพุต
nums = [0,1,5,0,3,8,0,0,9]
เอาต์พุต
[1,5,3,8,9,0,0,0,0]