How to efficiently remove duplicates from an array without using Set

后端 未结 30 2413
情深已故
情深已故 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:48

    This is an interview question :Remove duplicates from an array.I shall not use any Set or collections. The complete solution is :

    public class Test4 {
    public static void main(String[] args) {
         int a[] = {1, 2, 2, 3, 3, 3, 6,6,6,6,6,66,7,65}; 
                  int newlength =    lengthofarraywithoutduplicates(a);
                  for(int i = 0 ; i < newlength ;i++) {
                      System.out.println(a[i]);
                  }//for
    }//main
    
    private static int lengthofarraywithoutduplicates(int[] a) {
         int count = 1 ;
         for (int i = 1; i < a.length; i++) {
              int ch = a[i];
              if(ch != a[i-1]) {
                  a[count++] = ch;
              }//if
        }//for
        return count;
    
    }//fix
    
    }//end1
    

提交回复
热议问题