Finding an element in an array where every element is repeated odd number of times (but more than single occurrence) and only one appears once

后端 未结 5 1434
闹比i
闹比i 2020-12-12 10:25

You have an array in which every number is repeated odd number of times (but more than single occurrence). Exactly one number appears once. How do you find the number that a

5条回答
  •  孤城傲影
    2020-12-12 10:58

    Java, Correctness 100%, Performance 100%, Task score 100%

    // you can also use imports, for example:
    // import java.util.*;
    
    // you can write to stdout for debugging purposes, e.g.
    // System.out.println("this is a debug message");
    import java.util.HashMap;
    
    class Solution {
    
         /*Simple solution 
              Will be using HashMap(for performance) as Array, 
              only Key set is needed.
              Initially tried with ArryList but there was performance issue with
              that so switch to HashMap.
              Iterate over the given array and if item is there in key set         
              remove it(coz you found your pair) otherwise add as new Key.
              After full Iteration only one key will be there in the Map that is 
              your solution.
              In Short: If pair is found, remove it from Map's Key set,
              Last Key will be your solution
        */
        public int solution(int[] A) {
    
            //Map but used as Array
            final HashMap mapHave = new HashMap<>();
    
            //Iterate over given Array
            for (int nIdx = 0; nIdx < A.length; nIdx++) {
    
                //Current Item
                Integer nVal = A[nIdx];
    
                //Try to remove the current item, if item does not exists will
                //return null and if condition will be true
                if (mapHave.remove(nVal) == null) {
                    //current item not found, add it
                    mapHave.put(nVal, Boolean.TRUE);
                }
            }
    
            //There will be only one key remaining in the Map, that is
            //your solution
            return mapHave.keySet().iterator().next();
        }
    }
    

提交回复
热议问题