力扣链接
双循环暴力解法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40// // 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循环的工作
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38// // 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内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复