Lonely Integer

Sort by

recency

|

942 Discussions

|

  • + 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);            
    }
    
  • + 0 comments

    List< Integer> passedNumbers = new ArrayList<>(); for (int i = 0; i a.size(); i++) { if(!passedNumbers.contains(a.get(i))) { passedNumbers.add(a.get(i)); } else { passedNumbers.remove(a.get(i)); } } return passedNumbers.get(0)

  • + 0 comments

    JAVA

    for(Integer n: a){ int frec = Collections.frequency(a, n); if(frec==1){ num=n; } } return num;

  • + 0 comments

    Scala Solution

    def lonelyinteger(a: Array[Int]): Int = {
        // Write your code here)
            a.reduce(_^_)
        }
    
  • + 0 comments

    My Python solution using Mathematical logic:

    def lonelyinteger(a):
        '''
        Mathematical solution
        
        The sum of the elements of a is the sum of the
        doubles of each repeated element, plus the lonely (b)
        sum(a) = sum[2.x] + b
        
        The sum of the unique elements is the sum of all
        the unique elements that are repeated, plus the lonely (b)
        sum(set(a)) = sum[x] + b
        
        Then, 2*sum(set(a)) - sum(a) = b
        
        Time complexity: O(n)
        Space complexity: O(1)
        '''
        
        return 2*sum(set(a)) - sum(a)