概述
力扣链接
双循环暴力解法
//
// 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 << ']';
}
最后
以上就是欣喜墨镜为你收集整理的LeetCode--27.移除元素(C++)的全部内容,希望文章能够帮你解决LeetCode--27.移除元素(C++)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复