Tuesday, 14 March 2017

Find value that occurs in odd number of times in array of elements.



Given an array of Integers.Some Integers occurs even number of times and some odd.We need to find the number which occurs odd number of times.

Sample:-

Input:{1,2,3,2,3,1,2}

Output:2


Sample Program:

import java.util.HashSet;  
 import java.util.Set;  
 public class OddElements {  
      public static void main(String[] args) {  
           int[] integerArray={1,2,3,2,3,2,3};  
           printOddElementOccurence(integerArray);  
      }  
      private static void printOddElementOccurence(int[] integerArray) {  
        Set<Integer> unpaired = new HashSet<Integer>();  
        for (int i = 0; i<integerArray.length; i++){  
          if (unpaired.contains(integerArray[i])){  
            unpaired.remove(new Integer(integerArray[i]));  
          }else{  
            unpaired.add(integerArray[i]);  
          }  
        }  
        // all printed out values are odd  
        for (Integer result : unpaired){  
          System.out.println(result);  
        }   
      }  
 }  

Output:

 1  
 2  
 3  


Enjoy Learning.

No comments:

Post a Comment