C:如何删除1D数组中的相邻副本?

时间:2016-04-24 01:33:08

标签: c arrays

说我有一个数组:

int {2, 2, 2, 6, 6, 2, 2, 5, 5, 5}

我希望删除所有相邻重复项,以便它变为

int {2, 6, 2, 5}

我该怎么做?

2 个答案:

答案 0 :(得分:0)

不确定你尝试了什么。我的想法是这样的。

int i, num[] = {2, 2, 2, 6, 6, 2, 2, 5, 5, 5};

// Prepare new array for the result (result never larger than num[])
int *newNum = malloc(sizeof(num));
int used = 0, last = 0;

// Get number of elements in num[], which is 10 in this example
size_t n = sizeof(num) / sizeof(int);

for (i = 0; i < n; i++)
{
    if (num[i] != last)
    {
        newNum[used++] = num[i];
    }
    last = num[i];
}

printf("new array: \n");
for (i = 0; i < used; i++)
{
    printf("%i ", newNum[i]);
}

答案 1 :(得分:-1)

像这样:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
    int size = 10;
    int *array = memcpy(malloc(size * sizeof(*array)), (int[]){2, 2, 2, 6, 6, 2, 2, 5, 5, 5}, size * sizeof(*array));
    int i, new_size;

    for(i = new_size = 1; i < size; ++i){
        if(array[new_size-1] != array[i])
            array[new_size++] = array[i];
    }
    if(size > new_size){
        size = new_size;
        array = realloc(array, size * sizeof(*array));
    }
    for(i = 0; i < size; ++i)
        printf("%d ", array[i]);//2 6 2 5

    free(array);
    return 0;
}