Xor solution slower than hashset solution?


  • 2
    D

    At the beginning I use a HashSet:

    using System.Collections.Generic;
    
    public class Solution {
        public int SingleNumber(int[] nums) {
            var s=new HashSet<int>();
            foreach(var n in nums)
                if(s.Contains(n))
                    s.Remove(n);
                else
                    s.Add(n);
            var e=s.GetEnumerator();
            e.MoveNext();
            return e.Current;
        }
    }
    

    It takes 184ms.
    Later i use xor:

    using System.Collections.Generic;
    
    public class Solution {
        public int SingleNumber(int[] nums) {
            var i=0;
            foreach(var n in nums)
                i^=n;
            return i;
        }
    }
    

    It takes 192ms.
    The HashSet solution looks slower to me, because it contains function calls and HashSet operations, but it turns out to be faster. Any theory?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.