Lonely Integer

Sort by

recency

|

240 Discussions

|

  • + 0 comments

    Java using two hash sets which operations are O(1), therefore it is only needed to iterate whole array once.

    public static int lonelyinteger(List<Integer> arr) {
            HashSet<Integer> set = new HashSet<>();
            HashSet<Integer> uniqueSet = new HashSet<>();
            
            Integer unique = arr.get(0);
            Integer lastUnique = arr.get(0);
            
            for(Integer element: arr){
                if(!set.contains(element)){
                    set.add(element);
                    uniqueSet.add(element);
                }else{
                    uniqueSet.remove(element);
                }
            }
            
            return uniqueSet.stream().findFirst().get();
        }
    
  • + 0 comments
    public static int lonelyinteger(List<int> a)
        {
            int size = a.Count();
            if(size == 1) return a[0];
            int item = a[0];
            int count = 1;
            List<int> buffer = new List<int>{};
            for(int i = 0; i < size; i++){
                
                if(a[i] < -1 || a[i] > 101) throw new Exception("Invalid items");
                
                count = 1;
                if(buffer.Contains(a[i])) {
                    count++;
                    continue;
                }
                for(int j = i+1; j <= size - 1; j++){ 
                    if(a[i] == a[j]){
                        count++;
                        buffer.Add(a[i]);
                        break;
                    }
                }
                if(count < 2) item = a[i];
            }
            return item;
        }
    
  • + 0 comments
    def lonelyinteger(a):
        counter = dict()
        for num in a:
            counter[num] = counter.get(num, 0) +1
        return sorted(counter.items(), key= lambda x: x[1])[0][0]
    
  • + 0 comments
    function lonelyinteger(a) {
        let result,i,j;
        for(i=0; i<a.length; i++){
            let count = 0;
            for(j=0; j<a.length; j++){
                if(a[i]==a[j]){
                    count++;
                }
            }
            
            if(count==1){
                result = a[i];
            }
        }
        return result
    }
    
  • + 0 comments
    def lonelyinteger(a):
        unique=0
        for i in a:
            unique=i^unique
        return unique
            
    

    explanation : a^a=0 a^0=a...so if the element is unique we get the element as the result