ได้อาร์เรย์ nums และค่า val ลบค่า val ทุกตัวออกจากอาร์เรย์แบบ in-place คืนความยาวใหม่ (ลำดับอาจเปลี่ยนได้)
ตัวอย่าง
nums = [0,1,5,5,3,0,4,5], val = 5 → ความยาวใหม่ 5 (อาร์เรย์อาจเป็น [0,1,3,0,4,_,_,_])
ขั้นตอนการแก้ปัญหา (Two Pointers)
count = 0(ตำแหน่งเขียน)- วน
iทุกตำแหน่ง:- ถ้า
nums[i] != val:nums[count] = nums[i]; count += 1
- ถ้า
- คืน
count
การติดตั้งใน Python
class Solution:
def removeElement(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
return count
ob = Solution()
nums = [0,1,5,5,3,0,4,5]
print(ob.removeElement(nums, 5)) # 5
print(nums[:5]) # [0, 1, 3, 0, 4]
อินพุต / เอาต์พุต
Input: [0,1,5,5,3,0,4,5], 5 Output: 5