【LeetCode】27. Remove Element(移除元素)-C++实现的两种方法

问题描述:

 一、第一种解题方法

(1)使用双指针发

val = 3;

(2)若nums[i] = val 

i++,

(3)如果  nums[i] != val

则 nums[ j ] = nums[ i ]

然后 j++ ;

(4)完整的实现代码

#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>

using namespace std;


/// Two Pointers
///Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {

public:
    int removeElement(vector<int>& nums, int val) {

        int j = 0;
        for( int i = 0 ; i < nums.size() ; i ++ )
            if( nums[i] != val )
                nums[j++] = nums[i];

        return j;
    }
};


int main() {

    vector<int> nums = {3, 2, 2, 3};
    int val = 3;

    cout << Solution().removeElement(nums, val) << endl;

    return 0;
}

二、第二中解题方法

(1)现在考虑数组包含很少的要删除的元素的情况。例如,num=[1,2,3,5,4],Val=4num=[1,2,3,5,4],Val=4。之前的算法会对前四个元素做不必要的复制操作。另一个例子是 num=[4,1,2,3,5],Val=4num=[4,1,2,3,5],Val=4。似乎没有必要将 [1,2,3,5][1,2,3,5] 这几个元素左移一步

(2) val = 4

 while( i < j )

(3)如果nums[i] != val,

i ++;

(4)如果 nums[i] = val

则  nums[i] = nums[j]

然后j--;

(5)while( i < j )不成立,从而跳出循环

(6)代码的完整实现:

#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>

using namespace std;

/// Two Pointers
/// Move the deleted element to the last
/// This method would be save the unnecessary copy when the removed element is rare.
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {

public:
    int removeElement(vector<int>& nums, int val) {

        int j = nums.size();
        int i = 0;
        while( i < j )
            if( nums[i] == val )
                nums[i] = nums[--j];
            else
                i ++;

        return j;
    }
};


int main() {

    vector<int> nums = {1, 2, 3,5,4};
    int val = 4;

    cout << Solution().removeElement(nums, val) << endl;

    return 0;
}

参考资料:

1.https://leetcode-cn.com/problems/remove-element/solution/

2.https://github.com/liuyubobobo/Play-Leetcode

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值