Lonely Integer

Sort by

recency

|

918 Discussions

|

  • + 0 comments

    Python:

    def lonelyinteger(arr: list) -> int:
        """Using collections.Counter()."""
        for key, value in Counter(arr).items():
            if value == 1:
                return key
    
  • + 1 comment

    It didn't occur to me to xor the array. Has anyone here thought of it?

    Solution in c++.

    int lonelyinteger(vector a) {

    int unique = 0;
    
    for (int num : a) {
    
        unique ^= num;
    
    }
    return unique;
    

    }

  • + 1 comment

    Solution in Java

        int resultIndex = 0;
        Collections.sort(a);
    
        for (int i = 1; i < a.size(); i++) {
            if (!Objects.equals(a.get(i), a.get(i - 1))) {
                if (i == a.size() - 1){
                    resultIndex = i;
                    break;
                }
                if (!Objects.equals(a.get(i), a.get(i + 1))) {
                    resultIndex = i;
                    break;
                }
            }
        }
    
        return a.get(resultIndex);
    
  • + 0 comments

    It's rare to see, but Python has its own XOR operator!

    Just be aware that the following code does not works if the array has an element with more than two occurrences:

    def lonelyinteger(a):
        unique = 0
        for num in a:
            unique ^= num
        return unique
    
  • + 0 comments
    int result = 0;
    Dictionary<int, int> set = [];
    foreach (int integer in a)
    {
    	if (!set.ContainsKey(integer))
    	{
    		set.Add(integer, 1);
    	}
    	else
    	{
    		int value = set[integer];
    		set[integer] = ++value;
    	}
    }
    
    if (set.Count == 1)
    {
    	result = set.Keys.FirstOrDefault();
    }
    else
    {
    	result = set.Where(pair => pair.Value == 1).FirstOrDefault().Key;
    }
    
    return result;