The original problem of remove element of leetcode problem solving
Deletes an element of a particular value in an array, returning the deleted array length.
Note the point:
- The order of numbers after the operation does not need to be the same as before
- The part that exceeds the return length does not need to be processed
Example:
Input: Nums [1, 2, 3, 4, 3, 2, 1],val = 1
Output: 5
Thinking of solving problems
Around two pointers move toward the middle, the left pointer finds a value equal to Val, the right pointer finds the first value not equal to Val, and assigns the value to the left pointer to the right pointer. Keep moving toward the middle.
AC Source
class solution(object): def removeelement(self, nums, Val): "" : Type Nums:list[int]: type Val:int:rtype:int "" "left =0right = Len (nums)-1 whileLeft <= right: whileLeft <= Right andNums[left]! = val:left + =1 whileLeft <= Right andNums[right] = = val:right-=1 ifLeft < Right:nums[left] = Nums[right] Left + =1Right-=1 returnRight +1if__name__ = ="__main__":assertSolution (). Removeelement ([1,2,3,4,3,2,1],1) ==5 assertSolution (). Removeelement ([2],3) ==1
Welcome to my GitHub to get the relevant source code.
Leetcode Remove Element