Lonely Integer

Sort by

recency

|

227 Discussions

|

  • + 0 comments
    public static int lonelyinteger(List<Integer> a) {
        // Write your code here
        Collections.sort(a);
        System.out.println(a);
        if(a.size()==1){
            return a.get(0);
        }
        for(int i = 0 ; i < a.size() ; i++){
            if(i%2==0 && i<(a.size()-2)){
                if(a.get(i)==a.get(i+1)){
                    i++;
                }
                else{
                    return a.get(i);
                }
            }
        }
        return a.get(a.size()-1);
    
        }
    
  • + 0 comments

    I decided to reduce the time complexity using a set of a.

    a_set = set(a)
        for i in a_set:
            if a.count(i) == 1:
                return i
    
  • + 0 comments

    Time: O(N), Space: O(1)

    int lonelyinteger(vector a) { int ret {0};

    for (int num : a)
        ret ^= num;
    
    return ret;
    

    }

  • + 0 comments
    return a.GroupBy(x => x)
                    .Where(g => g.Count() == 1)
                    .Select(g => g.Key)
                    .FirstOrDefault();
    
  • + 0 comments

    Python 3 Solution.

    Using list comprehensions.

    • Time complexity of O(n^2)
    • Space Complexity of O(1)
    def lonelyinteger(a):
        loner = [value for value in a if a.count(value) == 1]
        return loner[0]