Click here to Skip to main content
15,912,756 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
We Have a Array say A ,In which some element are repeated so we want to remove repeation
Ex:a={1,2,3,1,6,2,6,9,6} OutPut:{1,2,3,6,9};'
Posted
Comments
Mohibur Rashid 17-Dec-11 23:57pm    
try yourself

You may:
  • Order the array (possibly using qsort).
  • Starting from the end, remove current item(*) if it is equal to previous one.


(*) To remove the current item (say item i, with 0 <= i < N):
a[k] = a[k+1],  with  i <= k < N-1
N = N-1
 
Share this answer
 
v3
Comments
[no name] 19-Dec-11 11:01am    
4! (-1 because complex solution for simple problem.)
CPallini 19-Dec-11 13:55pm    
Oh, 4! is more than 5, thank you. :-D
Albert Holguin 21-Dec-11 10:15am    
lol, 4! = 24
One way (probably not the most efficient, but it works) would be to create a new array and expand it as you add numbers. Every time you add something new, check to make sure it doesn't already exist in the new array.

There's some easy obvious optimizing you can do (and other tricks to make that faster), for example allocate the array's size some number of integers at a time (say 10) instead of reallocating every single instance and only reallocate when you're about to exceed that size. At the end, trim the excess memory with a realloc call.

There's probably other faster methods but that comes to mind off the back.
 
Share this answer
 
C++
int RemoveRep(int array[], int n)
  {
  int *arrayflag = (int *)malloc(n*sizeof(int));
  int left = 0, i = 0;
  while(i  arrayflag[i++] = false; //初始化标志数组
  for(i=0;i  {
  arrayflag[array[i]] = array[i]; //将出现过的数保存到对应的位置
  }
  for(i=0;i  {
  if(arrayflag[i] != false)
  array[left++] = arrayflag[i];
  }
  return left;
  }
 
Share this answer
 
Comments
Mohibur Rashid 18-Dec-11 1:34am    
not a good idea, to answer of homework. besided your code is full of bug

Or may be it what you want

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900