Skip to content

27. Remove Element

https://leetcode.com/problems/remove-element/

js
/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
  var left = 0
  var right = nums.length - 1

  while (left <= right) {
    if (nums[left] === val) {
      nums[left] = nums[right]
      right--
    } else {
      left++
    }
  }

  return right + 1
}
py
class Solution(object):

    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        left, right = 0, len(nums) - 1
        while left <= right:
            if nums[left] == val:
                nums[left] = nums[right]
                right -= 1
            else:
                left += 1
        return right + 1