Lonely Integer

  • + 0 comments
    public static int lonelyinteger(List<Integer> a) {
            // Sort list
            Collections.sort(a);
            //   Return first elem if size is one or second elem doesn't match
            int ans=a.get(0);
            if(a.size()==1 || a.get(0) != a.get(1))
                    return ans;
            // Iterate through list
            for(int i=1;i<a.size()-1;i++) {
            // Compare num before and after from index 1 - size-1
                    if(a.get(i)!= a.get(i-1) && a.get(i)!= a.get(i+1)){
            // If unequal return elem
                            return a.get(i);                
                    }
            }
            // If each elem has match but last return last
            return a.get(a.size()-1);            
    }