LeetCode--27.移除元素(C++)

力扣链接

双循环暴力解法

//
// Created by lwj on 2022-03-31.
//
#include <iostream>
#include <vector>
using namespace std;
// 时间复杂度:O(n^2)
// 空间复杂度:O(1)
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size(); // 把nums数组的大小赋值给size
        for (int i = 0; i < size; i++) {
            if (nums[i] == val) {
                for (int j = i; j < size - 1; j++) {
                    nums[j] = nums[j + 1];
                }
                i--;
                size--;
            }
        }
        return size;
    }
};
int main() {
    int a[] = {0, 1, 2, 3, 3, 0, 4, 2};
    vector<int> nums(a, a + sizeof(a) / sizeof(int)); // 第一个参数表示cost容器中放的是a数组,第二个参数表示是取a数组中的所有元素
    Solution solution;
    cout << solution.removeElement(nums, 2) << endl;
    int  len = solution.removeElement(nums,2);
    cout << '[';
    for (int i = 0; i < len; i++){
        cout << nums[i];
        if(i != (len - 1)) {
            cout << ' ';
        }
    }
    cout << ']';
}

双指针法,通过一个快指针和慢指针在一个for循环下完成两个for循环的工作

//
// Created by lwj on 2022-03-31.
//
#include <iostream>
#include <vector>
using namespace std;
// 时间复杂度:O(n)
// 空间复杂度:O(1)
// 快指针每一次循环都+1,慢指针每遇到与val值相同时就会停下,所以最后返回慢指针的值就是题目所求
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex++] = nums[fastIndex];
            }
        }
        return slowIndex;
    }

};
int main() {
    int a[] = {0, 1, 2, 3, 3, 0, 4, 2};
    vector<int> nums(a, a + sizeof(a) / sizeof(int)); // 第一个参数表示cost容器中放的是a数组,第二个参数表示是取a数组中的所有元素
    Solution solution;
    cout << solution.removeElement(nums, 2) << endl;
    int  len = solution.removeElement(nums,2);
    cout << '[';
    for (int i = 0; i < len; i++){
        cout << nums[i];
        if(i != (len - 1)) {
            cout << ' ';
        }
    }
    cout << ']';
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值