Find duplicate element in array in time O(n)

前端 未结 24 2921
余生分开走
余生分开走 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:00

    public class FindDuplicate {
        public static void main(String[] args) {
            // assume the array is sorted, otherwise first we have to sort it.
            // time efficiency is o(n)
            int elementData[] = new int[] { 1, 2, 3, 3, 4, 5, 6, 8, 8 };
            int count = 1;
            int element1;
            int element2;
    
            for (int i = 0; i < elementData.length - 1; i++) {
                element1 = elementData[i];
                element2 = elementData[count];
                count++;
                if (element1 == element2) {
                    System.out.println(element2);
                }
            }
        }
    }
    

提交回复
热议问题