如何从复杂度为O(n)的数组中删除重复元素,

时间:2016-10-21 18:27:54

标签: java data-structures

int [] ar = {4,5,6,2,3,2};

for (int i  = 0 ; i < ar.length ; i ++)
{   
    if (ar[Math.abs(ar[i])] >= 0 )
        ar[Math.abs(ar[i])] = -ar[Math.abs(ar[i])];
    else
        System.out.println(ar[i]);      
}

这不能给我确切的答案。

此外,目前没有任何答案是相关的。

1 个答案:

答案 0 :(得分:0)

    Integer [] ar = {4,5,6,2,3,2, 5, 7, 8, 5, 3, 2, 2};
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(ar));

    HashMap<Integer, Integer> seenBefore = new HashMap<>();
    //go through the array and determine the repeats
    for (int i  = 0 ; i < ar.length ; i ++)
    {   
       if(seenBefore.containsKey(ar[i]))
       {
           Integer count = seenBefore.get(ar[i]);
           count++;
           seenBefore.put(ar[i], count);
       }
       else{
           seenBefore.put(ar[i], 1);
       }
    }
    //now get ride of the repeats
    for(int i = 0; i < ar.length; i++)
    {
        if(seenBefore.containsKey(ar[i]) && seenBefore.get(ar[i]) > 1)
        {
            list.remove(new Integer(ar[i]));
            seenBefore.put(ar[i], seenBefore.get(ar[i]) - 1);
        }
    }

    System.out.println(list.toString());

由于我们有两个基于数组长度循环的for循环,因此我的大O复杂度为O(2n),即O(n)