从使用C数组中删除重复项 [英] Removing Duplicates from an Array using C

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

问题描述

我想小澄在C.数组概念 我有数组:

I want small clarification in array concept in C. I have array:

int a[11]={1,2,3,4,5,11,11,11,11,16,16};

我想结果是这样的:

I want result like this:

{1,2,3,4,5,11,16}

意味着我要删除重复。 这怎么可能?

Means I want remove duplicates. How is it possible?

推荐答案

您还不能轻易调整阵列在C中 - 至少,不是数组,因为你已经宣布之一。显然,如果数据按排序顺序,它是直接的将数据复制到所分配的阵列的前面,把它,如果它是正确的较小尺寸(它是一个线性O(n)的算法) 。如果数据未排序,它得混乱;琐碎的算法是二次的,所以也许一个排序(O(N LG N)),其次是线性算法是最适合的。

You can't readily resize arrays in C - at least, not arrays as you've declared that one. Clearly, if the data is in sorted order, it is straight-forward to copy the data to the front of the allocated array and treat it as if it was of the correct smaller size (and it is a linear O(n) algorithm). If the data is not sorted, it gets messier; the trivial algorithm is quadratic, so maybe a sort (O(N lg N)) followed by the linear algorithm is best for that.

您可以使用动态分配的内存来管理阵列。这可能是超出了,你在你的研究中已经达到了,虽然。

You can use dynamically allocated memory to manage arrays. That may be beyond where you've reached in your studies, though.

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

static int intcmp(const void *pa, const void *pb)
{
    int a = *(int *)pa;
    int b = *(int *)pb;
    if (a > b)
        return +1;
    else if (a < b)
        return -1;
    else
        return 0;
}

static int compact(int *array, int size)
{
    int i;
    int last = 0;
    assert(size >= 0);
    if (size <= 0)
        return size;
    for (i = 1; i < size; i++)
    {
        if (array[i] != array[last])
            array[++last] = array[i];
    }
    return(last + 1);
}

static void print(int *array, int size, const char *tag, const char *name)
{
   int i;
   printf("%s\n", tag);
   for (i = 0; i < size; i++)
       printf("%s[%d] = %d\n", name, i, array[i]);
}

int main(void)
{
   int a[11] = {1,2,3,4,5,11,11,11,11,16,16};
   int a_size = sizeof(a) / sizeof(a[0]);

   print(a, a_size, "Before", "a");
   a_size = compact(a, a_size);
   print(a, a_size, "After", "a");

   int b[11] = {11,1,11,3,16,2,5,11,4,11,16};
   int b_size = sizeof(b) / sizeof(b[0]);

   print(b, b_size, "Before", "b");
   qsort(b, b_size, sizeof(b[0]), intcmp);
   print(b, b_size, "Sorted", "b");
   b_size = compact(b, b_size);
   print(b, b_size, "After", "b");

   return 0;
}

这篇关于从使用C数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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