From 7eb033e69bfb2737cecbf0896e906cdb7b24adee Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Mon, 7 Feb 2022 09:30:18 +0800 Subject: [PATCH] add: 220206 --- 2202/220206.cpp | 37 +++++++++++++++++++++++++++++++++++++ 2202/CMakeLists.txt | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 2202/220206.cpp diff --git a/2202/220206.cpp b/2202/220206.cpp new file mode 100644 index 0000000..f0cc7a1 --- /dev/null +++ b/2202/220206.cpp @@ -0,0 +1,37 @@ +#include +#include + +/** + * 80. Remove Duplicates from Sorted Array II + * Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. + * Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. + * Return k after placing the final result in the first k slots of nums. + * Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. + */ + +class Solution { +public: + static int removeDuplicates(std::vector& nums) { + int prev, dup = 0; + for (auto it = nums.begin(); it != nums.end();) { + if (*it != prev) { + dup = 1; + prev = *(it++); + } else if (++dup >= 3) { + it = nums.erase(it, std::upper_bound(nums.begin(), nums.end(), *it)); + } else { + ++it; + } + } + return nums.size(); + } +}; + +int main() { + std::vector args {1,1,1,2,2,3}; + std::cout << Solution::removeDuplicates(args) << std::endl; + for (int i : args) { + std::cout << i << ' '; + } + return 0; +} diff --git a/2202/CMakeLists.txt b/2202/CMakeLists.txt index 3c7ae1d..a87229c 100644 --- a/2202/CMakeLists.txt +++ b/2202/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2202) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2202 220206-CN.cpp) +ADD_EXECUTABLE(2202 220206.cpp)