c++ - 如何从数组中删除 2 个连续的重复项?C++
问题描述
我有一个数组a={1,2,3,3,2,2,3,3}
,我需要像这样删除重复项:
1: a={1,2,2,2,3,3}
2: a={1,2,3,3}
3: a={1,2}
我需要删除 2 个连续的重复项:(1,2,3,3 将是 1,2),(1,2,2,2 将是 1,2)。
这是我的尝试,但如您所见,我需要一些帮助。
#include <iostream>
int main()
{
int n;
std::cin >> n;
int a[n];
for (int i = 0; i < n; i++)
std::cin >> a[i];
int i, j;
for (i = 0; i < n; i++)
if (a[i] == a[i + 1]) {
for (j = i + 1; j < n; j++)
a[j - 1] = a[j];
n--;
i--;
}
if (n != 0)
for (int i = 0; i < n; i++)
std::cout << a[i] << " ";
return 0;
}
我的问题是我不知道如何删除 2 个连续值。经过多次尝试,我无法解决此问题。先感谢您!
解决方案
我不会为你写代码,但这是我的想法。
首先,编写一个函数来检查是否存在“连续重复”:
//returns true if there are no consecutive duplicates within the array, false otherwise
func noConsecDups(arr a)
for int i = 0, i <= a.length-2, i++
if a[i] = a[i++]
return false
end of if
end of loop
return true
end function
现在,编写一个递归删除连续重复项的函数(可能不必递归执行,这只是我最初的想法),同时检查是否需要删除任何重复项!
//function that takes an array as input and returns the array with all consecutive duplicates removed
func removeConsecDups(arr a)
if a.length is 1, return a
if a.length is 2 and a[0] != a[1], return a
if(noConsecDups(a)) then there are no consecutive duplicates, return a
otherwise look through the array and just remove the first consecutive duplicates
for int j = 0, j <= a.length-2, j++
if a[j] = a[j+1]
remove a[j+1]
remove a[j]
break
end if statement
end loop
recursively call removeConsecDups(a)
end function
推荐阅读
- javascript - 如何在 next.js 中使用 package.json 中的代理?
- r - R:如何匹配给定范围内的多个变量
- postgresql - 为什么在 F# 中使用 `TransactionScope` 时 NpgsqlConnection 没有正确关闭或按时打开?
- string - 最长公共子序列(LCS)直觉
- verilog - 在verilog中写管道的两种方式,哪一种更好?
- android - 华为移动服务开发——存储服务不存在
- pandas - 通过 pandas.groupby.agg 循环时如何忽略单词的其他实例?
- powershell - Powershell > 并非每个代码路径都在方法中返回一个值
- perl - 如何防止 Mojolicious 缓存静态文件?
- maven - fabric8 docker-maven-plugin:从命令行添加附加标签