C:如何删除一维数组相邻的重复? [英] C: How to delete adjacent duplicates in 1D array?

查看:152
本文介绍了C:如何删除一维数组相邻的重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组:

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

和我想删除所有的相邻复制,使之成为

and I want to delete all the adjacent duplicates so that it becomes

int {2, 6, 2, 5}

我怎样才能做到这一点?

How can I do this?

推荐答案

不知道你已经尝试了什么。我的想法是这样的。

Not sure what you have tried. My idea would be like this.

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]);
}

这篇关于C:如何删除一维数组相邻的重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆