Lonely Integer

Sort by

recency

|

437 Discussions

|

  • + 0 comments
    function lonelyinteger(a: number[]): number {
        if (a.length === 1) return a[0];
        
        const arrMap = new Map<number, number>();
        
        a.forEach((n:number) => (arrMap.has(n)) ? arrMap.set(n, (arrMap.get(n) + 1)) : arrMap.set(n, 1));
        const iterator = arrMap.entries();
        
        for (let i = 0; i < arrMap.size; i++){
            const results = iterator.next().value;
            if (results[1] === 1) return results[0]
        }
    }
    
  • + 0 comments

    Scala code:

    def lonelyinteger(a: Array[Int]): Int = {
         val distinctElements = a.distinct
         val repeatElements = a.diff(distinctElements)
         val uniqueInteger = (distinctElements diff repeatElements)(0)
         uniqueInteger
        }
    
  • + 0 comments

    in JavaScript:

    function lonelyinteger(a) {
        const numOfIncidents = a.reduce((obj, int) => {
            obj[int] = (obj[int] || 0) + 1;
            return obj;
        }, {});
        
        for (let key in  numOfIncidents) {
             if (numOfIncidents[key] === 1){
                 return parseInt(key);
             }
         }
     }
    
  • + 1 comment

    JAVA: using XOR operator:

    public static int lonelyinteger(List a) {

        int result=a.get(0);
        for(int i=1;i<a.size();i++){
            result^=a.get(i);
        }
        return result;
    }
    
  • + 0 comments

    in C# public static int lonelyinteger(List a) {

    var cc = a.GroupBy(x => x).ToDictionary(g => g.Key, g => g.ToList());
    var dd = cc.Where(x => x.Value.Count == 1).ToList();
    return dd[0].Key;
    

    }