From 381117a18a750ba075771a709ddaa69a6d3e147c Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 15 Nov 2022 15:38:15 +0800 Subject: [PATCH] s0027 --- include/s0027_remove_element.hpp | 13 +++++++++++++ src/s0027_remove_element.cpp | 18 ++++++++++++++++++ tests/s0027_remove_element.cpp | 19 +++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 include/s0027_remove_element.hpp create mode 100644 src/s0027_remove_element.cpp create mode 100644 tests/s0027_remove_element.cpp diff --git a/include/s0027_remove_element.hpp b/include/s0027_remove_element.hpp new file mode 100644 index 0000000..26bd932 --- /dev/null +++ b/include/s0027_remove_element.hpp @@ -0,0 +1,13 @@ +#ifndef S0027_REMOVE_ELEMENT +#define S0027_REMOVE_ELEMENT + +#include + +using namespace std; + +class Solution { + public: + int removeElement(vector& nums, int val); +}; + +#endif diff --git a/src/s0027_remove_element.cpp b/src/s0027_remove_element.cpp new file mode 100644 index 0000000..046a457 --- /dev/null +++ b/src/s0027_remove_element.cpp @@ -0,0 +1,18 @@ +#include "s0027_remove_element.hpp" + +int Solution::removeElement(vector& nums, int val) { + int size = nums.size(); + if (size == 0) { + return 0; + } + int fast{0}, slow{0}; + for (; fast < size; ++fast) { + if (nums.at(fast) == val) { + continue; + } else { + nums[slow] = nums.at(fast); + ++slow; + } + } + return slow; +} diff --git a/tests/s0027_remove_element.cpp b/tests/s0027_remove_element.cpp new file mode 100644 index 0000000..265fe10 --- /dev/null +++ b/tests/s0027_remove_element.cpp @@ -0,0 +1,19 @@ +#include "s0027_remove_element.hpp" + +#include + +TEST(Problem27, Case1) { + vector nums{3, 2, 2, 3}; + int val{3}; + int o{2}; + Solution solution; + EXPECT_EQ(solution.removeElement(nums, val), o); +} + +TEST(Problem27, Case2) { + vector nums{0, 1, 2, 2, 3, 0, 4, 2}; + int val{2}; + int o{5}; + Solution solution; + EXPECT_EQ(solution.removeElement(nums, val), o); +}