Find duplicate element in array in time O(n)

前端 未结 24 2907
余生分开走
余生分开走 2020-11-27 10:07

I have been asked this question in a job interview and I have been wondering about the right answer.

You have an array of numbers from 0 to n-1, one o

24条回答
  •  时光取名叫无心
    2020-11-27 11:07

      public void duplicateNumberInArray {
        int a[] = new int[10];
        Scanner inp = new Scanner(System.in);
        for(int i=1;i<=5;i++){  
            System.out.println("enter no. ");
            a[i] = inp.nextInt();
        }
        Set st = new HashSet();
        Set s = new HashSet();
        for(int i=1;i<=5;i++){          
            if(!st.add(a[i])){
                s.add(a[i]);
            }
        }
    
        Iterator itr = s.iterator();
                    System.out.println("Duplicate numbers are");
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
    

    First of all creating an array of integer using Scanner class. Then iterating a loop through the numbers and checking if the number can be added to set (Numbers can be added to set only when that particular number should not be in set already, means set does not allow duplicate no. to add and return a boolean vale FALSE on adding duplicate value).If no. cannot be added means it is duplicate so add that duplicate number into another set, so that we can print later. Please note onething that we are adding the duplicate number into a set because it might be possible that duplicate number might be repeated several times, hence add it only once.At last we are printing set using Iterator.

提交回复
热议问题