Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/weixin_39675633/article/details/89463242
Delete any number of sorting an array of repeating numbers
problem
Given the array is sorted, remove duplicates, so that each element is present only dup_count and returns the new length.
- For example: dup_count = 1, known as the array input array A [1, 1, 2], the output of A [1, 2]
- For example: dup_count = 2, the input array is known array A [1, 1, 1, 2, 2, 3], the output of A [1, 1, 2, 2, 3]
- For example: dup_count = 3, the input array is known array A [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5], the output of A [1, 1, 1, 2 , 2, 3, 3, 3, 4, 4, 5]
void print(std::vector<int>& nums, const std::string& note)
{
std::cout << std::endl << note << std::endl;
for (int i = 0; i < nums.size(); ++i)
{
std::cout << nums[i] << ", ";
}
std::cout << std::endl;
}
int removeDuplicatesElem(std::vector<int>& nums, int dup_count = 2)
{
if (nums.size() <= dup_count)
return nums.size();
int index = dup_count;
for (int i = index; i < nums.size(); ++i)
{
if (nums[i] != nums[index - dup_count])
{
nums[index++] = nums[i];
}
}
return index;
}
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "Uage: ./demo dup_count" << std::endl;
return 1;
}
int dup_count = std::stoi(std::string(argv[1]));
std::cout << "please input a sorted array(int ): " << std::endl;
int elem;
std::vector<int> nums;
while (std::cin >> elem)
{
nums.push_back(elem);
}
print(nums, "output origen array:");
int n = removeDuplicatesElem(nums, dup_count);
for (int i = 0; i < n; i++)
std::cout << nums[i] << ", ";
std::cout << std::endl;
return 0;
}