How to efficiently remove duplicates from an array without using Set

后端 未结 30 2997
情深已故
情深已故 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条回答
  •  猫巷女王i
    2020-11-22 07:41

    public static void main(String args[]) {
        int[] intarray = {1,2,3,4,5,1,2,3,4,5,1,2,3,4,5};
    
        Set set = new HashSet();
        for(int i : intarray) {
            set.add(i);
        }
    
        Iterator setitr = set.iterator();
        for(int pos=0; pos < intarray.length; pos ++) {
            if(pos < set.size()) {
                intarray[pos] =setitr.next();
            } else {
                intarray[pos]= 0;
            }
        }
    
        for(int i: intarray)
        System.out.println(i);
    }
    

提交回复
热议问题