How to efficiently remove duplicates from an array without using Set

后端 未结 30 2808
情深已故
情深已故 2020-11-22 07:29

I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long ti

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 07:44

    you can take the help of Set collection

    int end = arr.length;
    Set set = new HashSet();
    
    for(int i = 0; i < end; i++){
      set.add(arr[i]);
    }
    

    now if you will iterate through this set, it will contain only unique values. Iterating code is like this :

    Iterator it = set.iterator();
    while(it.hasNext()) {
      System.out.println(it.next());
    }
    

提交回复
热议问题