删除重复的阵列中 [英] Deleting duplicates in the array

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

问题描述

我犯了一个程序在一个数组,但该计划的条件,如果要删除重复始终保持正确的。
我明白了什么问题通过malloc改变常用3 [I]给Arr [计数]和分配的内存,但程序打印数组,因为它是不删除重复项。

 #包括LT&;&stdio.h中GT;
    #包括LT&;&stdlib.h中GT;
    诠释计数= 0;
    无效删除(INT * ARR);
    无效搜索(INT * ARR);    诠释的main()
    {
    INT I;
    INT * ARR;
    ARR =(INT *)malloc的(的sizeof(INT));
    clrscr();
    的printf(请输入数组和preSS -1停止:\\ n); / *停止时发生-1 * /
    为(计数= 0;计数++)/ * count是数字的计数* /
    {
        scanf函数(%d个,&安培; ARR [计数]);
        realloc的(ARR,sizeof的((INT)+计数));
        fflush(标准输入);
        如果(*(ARR +计数)== - 1)/ *这种情况是不正确的* /
        打破;
    }
    搜索(ARR);
    对于(i = 0; I<计数;我++)
    {
        的printf(%d个\\ t的,编曲[I]);
    }
    残培();
    返回0;
}    搜索(ARR);
    对于(i = 0; I<计数;我++)
    {
        的printf(%d个,&安培;常用3 [I]);
    }
    残培();
    返回0;
}


解决方案

要删除阵列重复创建一个方法,即:


  • 排序数组

  • 计数唯一值

  • 创建一个新的数组,即大小唯一值

  • 开始应对从1阵列到另一个,当他们的价值观是不同的

要使用在C快速排序,你需要像比较器功能:

  INT补偿(常量无效* X,常量无效* Y){
  返回(*为(int *)x - *为(int *)Y);
}

然后你可以调用它:

 的qsort(数组,10的sizeof(INT),COMP);

要计数排序的数组的唯一项目,迭代这个数组,而这样做:

 如果(!sortedarray [I] = sortedarray [I + 1])计数++;

I made a program to delete duplicates in an array but the program's if condition always remain true. I understood what the problem was,changed arr[i] to arr[count] and allocated memory via malloc,but the program prints the array as it is without deleting the duplicates.

    # include<stdio.h>
    # include<stdlib.h>
    int count=0;
    void Delete(int *arr);
    void Search(int *arr);

    int main()
    {
    int i;
    int *arr;
    arr=(int*)malloc(sizeof(int));
    clrscr();
    printf("Enter array and press -1 to stop:\n");/*stops when -1 occurs*/
    for(count=0;    ;count++)/*count is the count of the numbers*/
    {
        scanf("%d",&arr[count]);
        realloc(arr,sizeof((int)+count));
        fflush(stdin);
        if(*(arr+count)==-1)/*This condition is never true.*/
        break;
    }
    Search(arr);
    for(i=0;i<count;i++)
    {
        printf("%d\t",arr[i]);
    }
    getch();
    return 0;
}

    Search(arr);
    for(i=0;i<count;i++)
    {
        printf("%d",&arr[i]);
    }
    getch();
    return 0;
}

解决方案

To remove duplicates from array create a method, that:

  • sorts the array
  • counts unique values
  • creates a new array, that is of size unique values
  • start coping from 1 array to the other, when their values are different

To use quicksort in c, you need comparator function like:

int comp(const void *x, const void *y) {
  return (*(int*)x - *(int*)y);
}

And then you can call it with:

qsort(array, 10, sizeof(int), comp);

To count unique items in sorted array, iterate over the array, and do something like:

if(sortedarray[i]!=sortedarray[i+1]) count++;

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

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