Algorithm: efficient way to remove duplicate integers from an array

前端 未结 30 2750
离开以前
离开以前 2020-11-22 16:03

I got this problem from an interview with Microsoft.

Given an array of random integers, write an algorithm in C that removes duplicated numbers an

30条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 16:22

    Given an array of n elements, write an algorithm to remove all duplicates from the array in time O(nlogn)

    Algorithm delete_duplicates (a[1....n])
    //Remove duplicates from the given array 
    //input parameters :a[1:n], an array of n elements.
    
    {
    
    temp[1:n]; //an array of n elements. 
    
    temp[i]=a[i];for i=1 to n
    
     temp[i].value=a[i]
    
    temp[i].key=i
    
     //based on 'value' sort the array temp.
    
    //based on 'value' delete duplicate elements from temp.
    
    //based on 'key' sort the array temp.//construct an array p using temp.
    
     p[i]=temp[i]value
    
      return p.
    

    In other of elements is maintained in the output array using the 'key'. Consider the key is of length O(n), the time taken for performing sorting on the key and value is O(nlogn). So the time taken to delete all duplicates from the array is O(nlogn).

提交回复
热议问题