leetcode27 Remove Element (删除目标元素)

题目要求:

给定一个数组和一个目标值,在数组内删除所有目标值项并返回不包含目标值的数组长度
不要为另一个数组分配额外的空间,保持空间复杂度是O(1)。

Example

输入 [3,2,2,3],val=3。输出:2
输入 [0,1,2,2,3,0,4,2],val=2 输出:5

解题思路

1.双指针法
参考26题leetcode26我们用一个指针来从前到后对数组进行遍历,另一个指针来记录非目标元素(最后指向末尾)

主要代码如下c++:
// leetcode 27
// Remove Element
class Solution {
public:
	int removeDuplicates(vector<int>& nums, int val) {
		int record = 0; // For record.
		for(int traverse = 0; traverse < nums.size(); ++traverse)
         {
             // consider whether is target val. 
             // record the non-target element and move.
             if(nums[traverse] != val) 
             nums[record++] = nums[traverse];
       } 
        	return record;
   }
};

2.迭代器法
思路一样,只不过换了更高效的迭代器来实现,最后返回不要弄错。

class Solution {
public:
	  int removeElement(vector<int>& nums, int val) {
	        vector<int>::iterator record, traverse;
	        for(record=traverse=nums.begin(); traverse != nums.end(); ++traverse)
	         {
	             if(*traverse == val)
	             { 
	             }
	            else{
	               *record = *traverse;                
	                record++; // to the next;
	            }
	       }
	       return record - nums.begin(); // to be noticed!
	    }
};

python 解法
in-place, two pointers!
注意,你要是使用内置函数remove的话,一次只能删除一个符合的元素,另外所以会进行递补,很容易进坑!!

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        l, r, count = 0, len(nums)-1, len(nums)
        while l<=r:
            while l<=r and nums[l] == val:
                l+=1
            while l<=r and nums[r] != val:
                r-=1
            if l < r:
                nums[l], nums[r] = nums[r], nums[l]
        for _ in range(l): # 删除前l个 val值
            del nums[0]
        return count - l

原题链接:https://leetcode.com/problems/remove-element/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值