20 ms C++ solution


  • 17
    L

    class Solution {

    public:

    vector<int> singleNumber(vector<int>& nums) {

        int xXor = nums[0];
        for (int i = 1; i<nums.size(); i++) {
            xXor = xXor ^ nums[i];
        }
        
        int marker = 1; 
        while ((marker & xXor) != marker) {
            marker = marker << 1;
        }
        
        int resultX = 0;
        for (int i = 0; i<nums.size(); i++) {
            if (nums[i] & marker) {
                resultX = resultX^nums[i];
            }
        }
        
        int resultY = resultX^xXor;
        
        return vector<int>{resultX, resultY};
    }
    

    };


  • 0
    L

    Great answer! And here is my version rewritten in C# if you do not mind:

       public int[] SingleNumber(int[] nums)
        {
            int result = 0;
    
            foreach (int num in nums)
            {
                result ^= num;
            }
    
            int marker = 1;
            while ((marker & result) != marker)
            {
                marker <<= 1;
            }
    
            int resultX = 0;
            foreach (int num in nums)
            {
                if ((num & marker) == marker)
                    resultX ^= num;
            }
    
            return new int[2] { resultX, resultX ^ result };
        }
    

    Thanks a lot!


Log in to reply
 

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