LeetCode Remove Element

Source: Internet
Author: User

LeetCode Remove Element
Remove Element for solving LeetCode Problems

Original question

Deletes an element of a specific value in an array and returns the length of the deleted array.

Note:

The order of numbers after the operation ends does not need to be processed for the part that exceeds the returned length.

Example:

Input: nums [1, 2, 3, 4, 3, 2, 1], val = 1
Output: 5

Solutions

The left and right pointers move closer to 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 pointed to by the right pointer to the left pointer. Continue to move closer to the center.

AC Source Code
class Solution(object):    def removeElement(self, nums, val):        """        :type nums: List[int]        :type val: int        :rtype: int        """        left = 0        right = len(nums) - 1        while left <= right:            while left <= right and nums[left] != val:                left += 1            while left <= right and nums[right] == val:                right -= 1            if left < right:                nums[left] = nums[right]                left += 1                right -= 1        return right + 1if __name__ == "__main__":    assert Solution().removeElement([1, 2, 3, 4, 3, 2, 1], 1) == 5    assert Solution().removeElement([2], 3) == 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.