Find duplicate element in array in time O(n)

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

    Traverse through the array and check the sign of array[abs(array[i])], if positive make it as negative and if it is negative then print it, as follows:

    import static java.lang.Math.abs;
    
    public class FindRepeatedNumber {
    
        private static void findRepeatedNumber(int arr[]) {
            int i;
            for (i = 0; i < arr.length; i++) {
                if (arr[abs(arr[i])] > 0)
                    arr[abs(arr[i])] = -arr[abs(arr[i])];
                else {
                    System.out.print(abs(arr[i]) + ",");
                }
            }
        }
    
        public static void main(String[] args) {
            int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
            findRepeatedNumber(arr);
        }
    }
    

    Reference: http://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/

提交回复
热议问题