从数组C中删除重复项 [英] Removing Duplicates from an array C

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

问题描述

我正在实现的代码应该删除已排序数组中的重复项。但它无法正常工作

这是代码

输出应为1 ,3,4但输出来的是1 1 3 3 4

需要帮助:)



The code i am implementing is supposed to remove the duplicates in an sorted array .But it does not work properly
Here is the code
The output should be 1,3,4 but instead the output coming is 1 1 3 3 4
Help needed :)

#include<stdio.h>

void remove_dup(int n ,int a[])
{
  int i=0,j=0;
  while(i<=n){
      if(a[i]==a[i+1])
	{
	  i=i+1;
	}
   else if(a[i]!=a[i+1])
	{
	  a[j]=a[i];
	  j++;
	  i++;
	  printf("%d\n",a[j]);	
}
    }
}
 int main()
  {
    int a[]={1,1,1,3,3,4,5};
    remove_dup(7,a);
  
}

推荐答案

首先,你不需要检查两次是否不同:

First off, you don't need to check if it is different twice:
if(a[i]==a[i+1])
   ...
else if(a[i]!=a[i+1])
   ...

与以下相同:

Is the same as:

if(a[i]==a[i+1])
   ...
else
   ...



其次,你期望的价值是错误的:你应该得到的不是1,3,4,而是3,4,5 - 这些是你需要移动的......

第三,你需要返回新的长度,或者外面的世界无法分辨出有多少独特的元素 - 外面的世界应该有多少数据现在进行。

第四,你需要检查你的值 - 你的while循环将运行在数组的末尾! :笑:

第五,使用更长,更有意义的名字也是一个好主意 - 当你阅读它时,它有助于自我纠正代码。

第六,让你的缩进正确,并且 在你的大括号定位中保持一致! 改变风格会让它变得更难,更难阅读...



所以,试试这个:


Second, the values you are expecting are wrong: it's not 1, 3, 4 you should get, but 3, 4, 5 - those are the ones you need to move...
Third, you need to return the new length, or the outside world can't tell how many unique elements there were - and so how much data the outside world should process now.
Fourth, you need to check your values - your while loop will run off the end of the array! :laugh:
Fifth, it's also a good idea to use longer, more meaningful names - it helps to self dcoument the code when you read it.
Sixth, get your indentation right, and be consistent in your curly bracket positioning! Having the style change makes it much, much harder to read...

So, try this:

#include <stdio.h>

int remove_dup(int count ,int arr[])
    {
    int in=0,out=0;
    while(in<count)
        {
        if(arr[in]!=arr[out])
            {
            out++;
            arr[out]=arr[in];
            }
        in++;
        }
    return out + 1;
    }
int main(void)
    {
    int index;
    int data[]={1,1,1,3,3,4,5};
    int newLen = remove_dup(7,data);
    for (index = 0; index < newLen; index++)
        {
        printf("%d,", data[index]);
        }
    printf("\nPress ENTER to close. ");
    getchar();

    return 0;
    }





在错误的地方关闭粗体:O - OriginalGriff [/ edit]



[edit]closing bold in wrong place :O - OriginalGriff[/edit]


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

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