首页 > 解决方案 > 如何从数组中删除 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 个连续值。经过多次尝试,我无法解决此问题。先感谢您!

标签: c++duplicates

解决方案


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

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

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

推荐阅读