如何从数组中删除2个连续重复项? C ++

时间:2018-06-12 20:08:36

标签: c++ duplicates

我有一个数组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个连续值。多次尝试后,我无法解决这个问题。先感谢您!

2 个答案:

答案 0 :(得分:1)

我不会为你编写代码,但这是我的想法。

首先,编写一个函数来检查是否存在“连续重复”:

//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

答案 1 :(得分:0)

如果您只需要最终结果(没有连续重复的数组),那么您最好的选择可能是使用堆栈并只遍历整个输入数组一次,将值与堆栈顶部进行比较并弹出重复项堆栈。

如果你需要在每个中间步骤之后打印出阵列状态,那么@ BarronDuBois的建议是可行的。

无论哪种方式代码本身都应该足够简单,我很乐意帮助解决任何具体问题。