C# solution using HashSet


  • 0
    T
    public class Solution {
        public int SingleNumber(int[] nums) {
            
            if (nums.Length == 0)
                return 0;
                
            if (nums.Length == 1)
                return nums[0];
            
            HashSet<int> hs = new HashSet<int>();
            
            for (int i = 0; i < nums.Length; i++)
            {
                if (!(hs.Add(nums[i])))
                    hs.Remove(nums[i]);
            }
            
            return hs.First();
        }
    }
    

  • 0
    U

    It's a good solution but the requirement states that the optimal solution is O(n) and uses no extra memory. However, for anyone who is not familiar with XOR bitwise operations, this is a good solution. Upvoting !


Log in to reply
 

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