[easy][Array][Two-Pointer]27. Remove Element

原题是:

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容