Simple solution using XOR


  • 0
    D
    public class Solution {  
        public int missingNumber(int[] nums) {  
            int r = 0;  
            for (int i = 0; i<nums.length; i++){  
                r ^=  i ^ nums[i];  
            }  
            return r ^ nums.length;  
        }  
    }  
    

    Python:

    class Solution(object):  
        def missingNumber(self, nums):  
            """ 
            :type nums: List[int] 
            :rtype: int 
            """  
            r = 0  
            for i in range(len(nums)):  
                r ^= i ^ nums[i]  
            return r ^ len(nums) 
    

    c++

    class Solution {  
    public:  
        int missingNumber(vector<int>& nums) {  
            int r = 0;   
            for (int i = 0; i<nums.size(); i++){  
                r ^= i ^ nums[i];  
            }  
            return r ^ nums.size();  
        }  
    };

Log in to reply
 

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