Remove elements

This commit is contained in:
Sainnhe Park 2022-11-24 17:21:25 +08:00
parent 56880d0095
commit 1e65cff7e5
6 changed files with 72 additions and 12 deletions

View File

@ -0,0 +1,13 @@
#ifndef S0283_MOVE_ZEROES_HPP
#define S0283_MOVE_ZEROES_HPP
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums);
};
#endif

View File

@ -1,6 +1,7 @@
# 数组 # 数组
- [二分查找](./bin_search.md) - [二分查找](./bin_search.md)
- [移除元素](./remove_elements.md)
# 经典代码 # 经典代码

View File

@ -0,0 +1,11 @@
# 移除元素
查找数组中的目标元素 target ,原地移除该元素,返回移除后的数组长度。
双指针法,快指针用于查找新数组的元素,即不是 target 的元素,慢指针用于覆盖,即写入新数组的元素。
## 相关题目
- [27. 移除元素](https://leetcode.com/problems/remove-element/)
- [24. 删除排序数组中的重复项](https://leetcode.com/problems/swap-nodes-in-pairs/)
- [283. 移动零](https://leetcode.com/problems/move-zeroes/)

View File

@ -1,18 +1,14 @@
#include "s0027_remove_element.hpp" #include "s0027_remove_element.hpp"
int Solution::removeElement(vector<int>& nums, int val) { int Solution::removeElement(vector<int>& nums, int val) {
int size = nums.size(); int len = nums.size();
if (size == 0) { int f{0}, s{0};
return 0; while (f < len) {
} if (nums[f] != val) {
int fast{0}, slow{0}; nums[s] = nums[f];
for (; fast < size; ++fast) { ++s;
if (nums.at(fast) == val) {
continue;
} else {
nums[slow] = nums.at(fast);
++slow;
} }
++f;
} }
return slow; return s;
} }

20
src/s0283_move_zeroes.cpp Normal file
View File

@ -0,0 +1,20 @@
#include "s0283_move_zeroes.hpp"
void Solution::moveZeroes(vector<int>& nums) {
int len = nums.size();
if (len <= 1) {
return;
}
int s{0}, f{0};
while (f < len) {
if (nums[f] != 0) {
nums[s] = nums[f];
++s;
}
++f;
}
while (s < len) {
nums[s] = 0;
++s;
}
}

View File

@ -0,0 +1,19 @@
#include "s0283_move_zeroes.hpp"
#include <gtest/gtest.h>
TEST(Problem283, Case1) {
vector<int> i{0, 1, 0, 3, 12};
vector<int> o{1, 3, 12, 0, 0};
Solution solution;
solution.moveZeroes(i);
EXPECT_EQ(i, o);
}
TEST(Problem283, Case2) {
vector<int> i{0};
vector<int> o{0};
Solution solution;
solution.moveZeroes(i);
EXPECT_EQ(i, o);
}