Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

error in slow-fast pointer in element removal #2477

Open
ccccclw opened this issue Mar 12, 2024 · 0 comments
Open

error in slow-fast pointer in element removal #2477

ccccclw opened this issue Mar 12, 2024 · 0 comments

Comments

@ccccclw
Copy link

ccccclw commented Mar 12, 2024

If the target val is the last element of array, then it will not be removed in the python snippet.

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        # 快慢指针
        fast = 0  # 快指针
        slow = 0  # 慢指针
        size = len(nums)
        counter = 0
        while fast < size:  # 不加等于是因为,a = size 时,nums[a] 会越界
            # slow 用来收集不等于 val 的值,如果 fast 对应值不等于 val,则把它与 slow 替换
            if nums[fast] != val:
                nums[slow] = nums[fast]
                slow += 1
            else:
                counter += 1
            fast += 1
        return slow[:-1*counter]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant