1. Given an array of numbers ranging from 1 to N, in which numbers could repeat itself any number of times, find the duplicate numbers in O(n) with constant memory space.
Method 1: Use an extra array keep track of the elements counting.
public class Duplicate { public static void main(String args[]) { int arr[] = {1, 3, 5, 8, 5, 7, 4, 2, 4}; findDuplicate(arr); } public static void findDuplicate(int arr[]) { // Using the current number as the key/index to the value for(int i = 0; i < arr.length; i++) { // Positvie - never seen before if( arr[Math.abs(arr[i]) - 1] > 0 ) { arr[Math.abs(arr[i]) - 1] = -arr[Math.abs(arr[i]) - 1]; } // Negative - already seen, duplicate else if(arr[Math.abs(arr[i]) - 1] < 0) { System.out.print(Math.abs(arr[i]) + " "); arr[Math.abs(arr[i]) - 1] = 0; } else {// 0 - already detected } } System.out.println(); } }output:
5 4
No comments:
Post a Comment