leetcode27-移除元素(c++\python)

题目

思路

首先从题干中找出关键信息:

  • 原地删除
  • 不使用额外的数组空间

本题与leetcode26(传送门)、leetcode80(传送门)类似,继续采用快慢指针法。设定快慢指针:fats和slow,让fast去探路,根据是否找到目标数,然后决定slow要不要前进,此处fast不再与前后元素比较,而是寻找目标数,因此fast和slow都从0开始,注意细节变化。

题解

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int n=nums.size();
        if(n==0) return 0;
        int fast=0,slow=0;
        while(fast<n)
        {
            if(nums[fast]!=val)
            {
                nums[slow++]=nums[fast];
            }
            fast++;
        }
        return slow;
    }
};

Python:

class Solution(object):
    def removeElement(self, nums, val):
        n=len(nums)
        if(n==0):
            return 0
        fast,slow=0,0
        while(fast<n):
            if(nums[fast]!=val):
                nums[slow]=nums[fast]
                slow+=1
            fast+=1
        return slow

参考

  1. https://leetcode-cn.com/problems/remove-element/
posted @ 2020-03-12 10:08  depth-perception  阅读(152)  评论(0)    收藏  举报