How to efficiently remove duplicates from an array without using Set

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

    This is simple way to sort the elements in the array

    public class DublicatesRemove {
        public static void main(String args[]) throws Exception {
    
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("enter size of the array");
            int l = Integer.parseInt(br.readLine());
            int[] a = new int[l];
            // insert elements in the array logic
            for (int i = 0; i < l; i++) 
            {
                System.out.println("enter a element");
                int el = Integer.parseInt(br.readLine());
                a[i] = el;
            }
            // sorting elements in the array logic
            for (int i = 0; i < l; i++) 
            {
                for (int j = 0; j < l - 1; j++) 
                {
                    if (a[j] > a[j + 1])
                    {
                        int temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }
            }
            // remove duplicate elements logic
            int b = 0;
            a[b] = a[0];
            for (int i = 1; i < l; i++)
            {
                if (a[b] != a[i])
                {
                    b++;
                    a[b]=a[i];
    
                }
    
            }
            for(int i=0;i<=b;i++)
            {
                System.out.println(a[i]);
            }
    
    
        }
    }
    

提交回复
热议问题