美文网首页
[easy][Array][Two-Pointer]27. Re

[easy][Array][Two-Pointer]27. Re

作者: 小双2510 | 来源:发表于2017-11-23 05:08 被阅读0次

原题是:

Given an array and a value, remove all instances of that value
in-placeand return the new length.
Do not allocate extra space for another array, you must do this by
modifying the input arrayin-placewith O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:

Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.

思路:

这个题与26题一样,都是比较经典的两指针思想。
i指针守住需要更新的位置,j指针去寻找符合条件的元素回来给i所在的位置。
注意这一题,由于自己设计的逻辑,需要返回的是i,而不再是i+1

代码是:

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i,j = 0,0
        while j < len(nums):
            if nums[j] != val:
                nums[i] = nums[j]
                i += 1
                j += 1
            else:
                j += 1
        
        return i

相关文章

网友评论

      本文标题:[easy][Array][Two-Pointer]27. Re

      本文链接:https://www.haomeiwen.com/subject/fxuavxtx.html