Algorithm to remove elements (Python implementation)

foreword

  • No.: 27. Remove elements
  • Link: leetcode link
  • Description: Given you an array nums and a value val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.
    Don't use extra array space, you have to use only O(1) extra space and modify the input array in-place

train of thought

1. Violent loop, the outer loop traverses the array, and the inner loop updates the array
2. Double pointers, the fast pointer is the index to traverse the array, and the slow pointer is the index to update the array (adopted)

the code

class Solution:
	def removeElement(self, nums:List[int], val int) -> int:
		fast, slow = 0
		while fast < len(nums):
			if nums[fast] != val:
				num[slow] = nums[fast]
				slow += 1
			fast += 1
		return slow
		

Guess you like

Origin blog.csdn.net/sinat_34388320/article/details/125523027