-6

Below code snippets shows how to remove duplicate integers from an array without using any collections such as HashSet, ArrayList etc...

Avinash Pande
  • 1,510
  • 19
  • 17

1 Answers1

-4
public class UniqueElementinAnArray 
{
    public static void main(String[] args) 
    {
        int[] a = {10,10,10,10,10,100};
        int[] output = new int[a.length];
        int count = 0;
        int num = 0;

        //Iterate over an array
        for(int i=0; i<a.length; i++)
        {
            num=a[i];
            boolean flag = check(output,num);
            if(flag==false)
            {
                output[count]=num;
                ++count;
            }

        }

        //print the all the elements from an array except zero's (0)
        for (int i : output) 
        {
            if(i!=0 )
                System.out.print(i+"  ");
        }

    }

    /***
     * If a next number from an array is already exists in unique array then return true else false
     * @param arr   Unique number array. Initially this array is an empty.
     * @param num   Number to be search in unique array. Whether it is duplicate or unique.
     * @return  true: If a number is already exists in an array else false 
     */
    public static boolean check(int[] arr, int num)
    {
        boolean flag = false;
        for(int i=0;i<arr.length; i++)
        {
            if(arr[i]==num)
            {
                flag = true;
                break;
            }
        }
        return flag;
    }

}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Avinash Pande
  • 1,510
  • 19
  • 17
  • I am telling without using any collections. please read question properly. You have given reference of a question which has most of the answers are irrelevant. check those answers. I checked thats the reason I have added new question. – Avinash Pande Apr 19 '18 at 14:16
  • 2
    Then let my ask you a question: where do you **remove** anything from the given array? the array remains the same...you're just printing values. clearly not solved the task at hand – UninformedUser Apr 19 '18 at 14:18
  • Sir, please execute above code using any java editor you will get to see. – Avinash Pande Apr 19 '18 at 14:19
  • 2
    Formally, you're creating a new array and always check whether the value already exists in, if not add the value - that's neither overwhleming nor black magic. Now the interesting part: How did you measure efficiency compared to other methods? Any benchmarks? – UninformedUser Apr 19 '18 at 14:22
  • I didn't used any collections so all the data resides in stack only. it improves efficiency. – Avinash Pande Apr 19 '18 at 14:24