数组删除重复元素

时间:2010-07-28 07:12:06

标签: algorithm arrays data-structures

我有一个未排序的数组,如果存在,删除元素的所有重复项的最佳方法是什么?

e.g:

a[1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3]

所以在那个操作之后,数组应该看起来像

 a[1,5,2,6,8,9,10,3,4,11]

13 个答案:

答案 0 :(得分:73)

检查每个元素与其他所有元素

天真的解决方案是针对每个其他元素检查每个元素。即使您只是“前进”,这也是浪费并产生O(n 2 )解决方案。

排序然后删除重复项

更好的解决方案是对数组进行排序,然后将每个元素检查到它旁边的元素以查找重复项。选择一种有效的排序,这是O(n log n)。

基于排序的解决方案的缺点是订单未得到维护。然而,额外的步骤可以解决这个问题。将所有条目(在唯一排序的数组中)放入具有O(1)访问权限的哈希表中。然后迭代原始数组。对于每个元素,检查它是否在哈希表中。如果是,请将其添加到结果中并将其从哈希表中删除。您将得到一个结果数组,该数组具有原始数据的顺序,每个元素与第一次出现的位置相同。

线性整数

如果你正在处理一些固定范围的整数,你可以通过使用基数排序做得更好。例如,如果假设数字都在0到1,000,000的范围内,则可以分配大约1,000,001的位向量。对于原始数组中的每个元素,您可以根据其值设置相应的位(例如,设置第14位时值为13)。然后遍历原始数组,检查它是否在位向量中。如果是,则将其添加到结果数组中并从位向量中清除该位。这是O(n)并且交易空间。

哈希表解决方案

这导致我们找到最好的解决方案:排序实际上是一种分心,虽然有用。创建具有O(1)访问权限的哈希表。遍历原始列表。如果它不在哈希表中,则将其添加到结果数组并将其添加到哈希表中。如果它在哈希表中,请忽略它。

这是迄今为止最好的解决方案。那为什么其余的呢?因为这样的问题是关于调整你已经(或者应该)知识的知识,并根据你在解决方案中做出的假设来改进它们。发展解决方案并理解其背后的思想远比回流解决方案更有用。

此外,哈希表并不总是可用。采用嵌入式系统或空间非常有限的东西。您可以在少数操作码中实现快速排序,远远少于任何哈希表。

答案 1 :(得分:2)

这可以使用基于散列表的集合在摊销的O(n)中完成。

伪代码:

s := new HashSet
c := 0
for each el in a
  Add el to s.
    If el was not already in s, move (copy) el c positions left.
    If it was in s, increment c. 

答案 2 :(得分:2)

如果您不需要保留原始对象,则可以循环它并创建一个新的唯一值数组。在C#中使用List来访问所需的功能。它不是最具吸引力或最智能的解决方案,但它确实有效。

int[] numbers = new int[] {1,2,3,4,5,1,2,2,2,3,4,5,5,5,5,4,3,2,3,4,5};
List<int> unique = new List<int>();

foreach (int i in numbers)
     if (!unique.Contains(i))
          unique.Add(i);

unique.Sort();
numbers = unique.ToArray();

答案 3 :(得分:1)

将数字视为键。

for each elem in array:
if hash(elem) == 1 //duplicate
  ignore it
  next
else
  hash(elem) = 1
  add this to resulting array 
end
如果您了解数字范围等数据以及是否有限,那么您可以使用ZERO初始化该大数组。
array flag[N] //N is the max number in the array
for each elem in input array:
  if flag[elem - 1] == 0
    flag[elem - 1] = 1
    add it to resulatant array
  else
    discard it //duplicate
  end

答案 4 :(得分:1)

    indexOutput = 1;
    outputArray[0] = arrayInt[0];
    int j;
    for (int i = 1; i < arrayInt.length; i++) {            
        j = 0;
        while ((outputArray[j] != arrayInt[i]) && j < indexOutput) {
            j++;
        }
        if(j == indexOutput){
           outputArray[indexOutput] = arrayInt[i];
           indexOutput++;
        }         
    }

答案 5 :(得分:0)

使用Set实现。
如果是Java,则HashSetTreeSetLinkedHashSet

答案 6 :(得分:0)

我同意Cletus。使用QuickSort,然后删除重复

答案 7 :(得分:0)

这是我用C ++创建的代码段,试试吧

#include <iostream>

using namespace std;

int main()
{
   cout << " Delete the duplicate" << endl; 

   int numberOfLoop = 10;
   int loopCount =0;
   int indexOfLargeNumber = 0;
   int largeValue = 0;
   int indexOutput = 1;

   //Array to hold the numbers
   int arrayInt[10] = {};
   int outputArray [10] = {};

   // Loop for reading the numbers from the user input
   while(loopCount < numberOfLoop){       
       cout << "Please enter one Integer number" << endl;
       cin  >> arrayInt[loopCount];
       loopCount = loopCount + 1;
   }



    outputArray[0] = arrayInt[0];
    int j;
    for (int i = 1; i < numberOfLoop; i++) {            
        j = 0;
        while ((outputArray[j] != arrayInt[i]) && j < indexOutput) {
            j++;
        }
        if(j == indexOutput){
           outputArray[indexOutput] = arrayInt[i];
           indexOutput++;
        }         
    }

   cout << "Printing the Non duplicate array"<< endl;

   //Reset the loop count
   loopCount =0;

   while(loopCount < numberOfLoop){ 
       if(outputArray[loopCount] != 0){
        cout <<  outputArray[loopCount] << endl;
    }     

       loopCount = loopCount + 1;
   }   
   return 0;
}

答案 8 :(得分:0)

我的解决方案(O(N))不使用额外的内存,但必须对数组进行排序(我的类使用插入排序算法,但它并不重要。):

  public class MyArray
        {
            //data arr
            private int[] _arr;
            //field length of my arr
            private int _leght;
            //counter of duplicate
            private int countOfDup = 0;
            //property length of my arr
            public int Length
            {
                get
                {
                    return _leght;
                }
            }

            //constructor
            public MyArray(int n)
            {
                _arr = new int[n];
                _leght = 0;
            }

            // put element into array
            public void Insert(int value)
            {
                _arr[_leght] = value;
                _leght++;
            }

            //Display array
            public void Display()
            {
                for (int i = 0; i < _leght; i++) Console.Out.Write(_arr[i] + " ");
            }

            //Insertion sort for sorting array
            public void InsertSort()
            {
                int t, j;
                for (int i = 1; i < _leght; i++)
                {
                    t = _arr[i];
                    for (j = i; j > 0; )
                    {
                        if (_arr[j - 1] >= t)
                        {
                            _arr[j] = _arr[j - 1];
                            j--;
                        }
                        else break;
                    }
                    _arr[j] = t;
                }
            }

            private void _markDuplicate()
            {
                //mark duplicate Int32.MinValue
                for (int i = 0; i < _leght - 1; i++)
                {
                    if (_arr[i] == _arr[i + 1])
                    {
                        countOfDup++;
                        _arr[i] = Int32.MinValue;
                    }
                }
            }

            //remove duplicates O(N) ~ O(2N) ~ O(N + N)
            public void RemoveDups()
            {
                _markDuplicate();
                if (countOfDup == 0) return; //no duplicate
                int temp = 0;

                for (int i = 0; i < _leght; i++)
                {
                    // if duplicate remember and continue
                    if (_arr[i] == Int32.MinValue) continue;
                    else //else need move 
                    {
                        if (temp != i) _arr[temp] = _arr[i];
                        temp++;
                    }
                }
                _leght -= countOfDup;
            }
        }

主要

static void Main(string[] args)
{
     Random r = new Random(DateTime.Now.Millisecond);
     int i = 11;
     MyArray a = new MyArray(i);
     for (int j = 0; j < i; j++)
     {
        a.Insert(r.Next(i - 1));
     }

     a.Display();
     Console.Out.WriteLine();
     a.InsertSort();
     a.Display();
     Console.Out.WriteLine();
     a.RemoveDups();
     a.Display();

    Console.ReadKey();
}

答案 9 :(得分:0)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class testing {
    public static void main(String[] args) {
        EligibleOffer efg = new EligibleOffer();
        efg.setCode("1234");
        efg.setName("hey");
        EligibleOffer efg1 = new EligibleOffer();
        efg1.setCode("1234");
        efg1.setName("hey1");
        EligibleOffer efg2 = new EligibleOffer();
        efg2.setCode("1235");
        efg2.setName("hey");
        EligibleOffer efg3 = new EligibleOffer();
        efg3.setCode("1235");
        efg3.setName("hey");
        EligibleOffer[] eligibleOffer = { efg, efg1,efg2 ,efg3};
        removeDupliacte(eligibleOffer);
    }

    public static EligibleOffer[] removeDupliacte(EligibleOffer[] array) {
        List list = Arrays.asList(array);
        List list1 = new ArrayList();
        int len = list.size();
        for (int i = 0; i <= len-1; i++) {
            boolean isDupliacte = false;
            EligibleOffer eOfr = (EligibleOffer) list.get(i);
            String value = eOfr.getCode().concat(eOfr.getName());
            if (list1.isEmpty()) {
                list1.add(list.get(i));
                continue;
            }
            int len1 = list1.size();
            for (int j = 0; j <= len1-1; j++) {
                EligibleOffer eOfr1 = (EligibleOffer) list1.get(j);
                String value1 = eOfr1.getCode().concat(eOfr1.getName());
                if (value.equals(value1)) {
                    isDupliacte = true;
                    break;
                }
                System.out.println(value+"\t"+value1);
            }
            if (!isDupliacte) {
                list1.add(eOfr);
            }
        }
        System.out.println(list1);
        EligibleOffer[] eligibleOffer = new EligibleOffer[list1.size()];
        list1.toArray(eligibleOffer);
        return eligibleOffer;
    }
}

答案 10 :(得分:0)

Time O(n) space O(n) 

#include <iostream>
    #include<limits.h>
    using namespace std;
    void fun(int arr[],int size){

        int count=0;
        int has[100]={0};
        for(int i=0;i<size;i++){
            if(!has[arr[i]]){
               arr[count++]=arr[i];
               has[arr[i]]=1;
            }
        }
     for(int i=0;i<count;i++)
       cout<<arr[i]<<" ";
    }

    int main()
    {
        //cout << "Hello World!" << endl;
        int arr[]={4, 8, 4, 1, 1, 2, 9};
        int size=sizeof(arr)/sizeof(arr[0]);
        fun(arr,size);

        return 0;
    }

答案 11 :(得分:0)

public class RemoveDuplicateArray {
    public static void main(String[] args) {
        int arr[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 9 };
        int size = arr.length;
        for (int i = 0; i < size; i++) {
            for (int j = i+1; j < size; j++) {
                if (arr[i] == arr[j]) {
                    while (j < (size) - 1) {
                        arr[j] = arr[j + 1];
                        j++;
                    }
                    size--;
                }
            }
        }
        for (int i = 0; i < size; i++) {
            System.out.print(arr[i] + "  ");
        }
    }

}
  

输出 - 1 2 3 4 5 6 7 9

答案 12 :(得分:0)

你可以在python中使用“in”和“not in”语法,这使得它非常简单。

复杂度高于散列方法,因为“not in”等同于线性遍历以确定该条目是否存在。

li = map(int, raw_input().split(","))
a = []
for i in li:
    if i not in a:
        a.append(i)
print a
相关问题