Tuesday, November 22, 2011

Two non-repeating elements in an array


package arrays;

import java.util.HashMap;
import java.util.Map;


/**
 * @author ssundara
 *
 */
public class Two_non_rep {
 
  /**
   * @param args
   */
  public static void main(String args[]){

  int a[] = {2, 4, 7, 9, 2, 4};
 
  // METHOD 1
  int xor = a[0];
  for(int i=1;i < a.length;i++)
    xor = xor ^ a[i];
  // output xor will have the bits set on places where the bits of two non rep_no are differing.
  System.out.println(xor);
 
 
  //find d rightmost set bit, since finding tat ll be easy
  int rightmost_set_bit;
  rightmost_set_bit = xor & ~(xor-1);
  System.out.println(rightmost_set_bit);
 
  // x n y will have non rep_nos
  int x = 0,y = 0;
  for(int j = 0;j < a.length; j++){
    if((a[j] & rightmost_set_bit)!=0)
      x ^= a[j];
    else
      y ^= a[j];
 
}
  System.out.println("Two non rep nos are : :" + x + "," + y);

 
  // METHOD 1
 
  Map<Integer,Integer> map= new HashMap<Integer,Integer>();
  Integer count;
  for(int i=0;i < a.length;i++){
     count = map.get(a[i]);
     map.put(a[i], count == null ? 1 :count + 1);
  }
  System.out.println("Using Hashmap");
  for(int i=0;i < a.length;i++)
    if(map.get(a[i])==1)
       System.out.println(a[i]);
}
}

No comments:

Post a Comment