Accepted 36ms c++ solution, just one line.


  • 0

    This problem is very similar with Single Number. After we push 0, 1, 2, ..., n into the array, every element appears twice except for the answer. So we can solve the problem by using XOR, just like this discussion.

    class Solution {
    public:
        int missingNumber(std::vector<int>& nums) {
    		int i = 0, res = 0;
    		while (i != nums.size()) {
    			res ^= nums[i] ^ i++;
    		}
            return res ^ i;
        }
    };
    

    In fact, we can also solve this problem by summation, and only need one line of code.

    class Solution {
    public:
        int missingNumber(std::vector<int>& nums) {
    		return (nums.size() + 1) * nums.size() / 2 - std::accumulate(nums.begin(), nums.end(), 0);
        }
    };
    

Log in to reply
 

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