2017-07-06 48 views
-9

我要一些逻辑将所述阵列中插入数字,并在同一时间它会检查当前的号码已不存在在数组中。请帮助我的逻辑。如何避免C数组中的重复元素项?

+1

显示你的努力。 – rsp

+2

你到目前为止尝试过什么?你的尝试如何工作,或没有工作?请花些时间阅读[帮助页面](http://stackoverflow.com/help),尤其是名为[“我可以问些什么话题?”]的章节(http://stackoverflow.com/help/)讨论话题)和[“我应该避免问什么类型的问题?”](http://stackoverflow.com/help/dont-ask)。另外[阅读关于如何提出好问题](http://stackoverflow.com/help/how-to-ask)。最后,请学习如何创建[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。 –

+0

http://www.studytonight.com/c/remove-duplicate-element-program.php – rsp

回答

0

代码以在数组中删除重复的元素

#include<stdio.h> 
    #include<conio.h> 
    void main() 
    { 
     int a[20], i, j, k, n; 
     clrscr(); 

     printf("\nEnter array size : "); 
     scanf("%d",&n); 

     printf("\nEnter %d array element : ", n); 
     for(i = 0; i < n; i++) 
     { 
      scanf("%d",&a[i]); 
     } 

     printf("\nOriginal array is : "); 
     for(i=0;i< n;i++) 
     { 
      printf(" %d",a[i]); 
     } 

     printf("\nNew array is : "); 
     for(i=0; i < n; i++) 
     { 
      for(j=i+1; j < n;) 
      { 
      if(a[j] == a[i]) 
      { 
       for(k=j; k < n;k++) 
       { 
        a[k] = a[k+1]; 
       } 
       n--; 
      } 
      else { 
       j++; 
      } 
      } 
     } 

     for(i=0; i < n; i++) 
     { 
      printf("%d ", a[i]); 
     } 
    getch(); 
    } 

输出

输入数组大小:5

输入5的数组元素:11 13 11 12 13

原始阵列是:11 13 11 12 13

新阵列是:11 13 12

0

可能的解决方案:

  1. O(n^2)算法,在这里做线性搜索O(n)检查该号码是否存在于阵列中或不是所有的n元素。

对于每个元素(n个元素):

O(n):搜索

O(1):插入

  • O(n^2)算法,当你在排序后的数组插入。
  • 对于每个元素(n个元素):

    O(log n):二进制搜索

    O(n):移动和插入

    虽然有先进的数据结构(更多在C++ STL),但你将需要的不仅仅是一个数组。因为在数组中插入代价很大(在特定位置插入)。

    其他数据结构这可能帮助:BST(AVL-BST,伸展树......等平衡树结构)。

    在C++:套正是你想要的。集合在STL中作为树实现。