268 Missing Number

Missing Number
数组中包含n个0-N不同元素,找到缺失的元素

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int sum = (1 + nums.size())*nums.size()/2;
        int s = 0;
        for (int i = 0; i < nums.size(); i++){
            s += nums[i];
        }
        return sum - s;
    }
};

solution中另一种位XOR解法:
以[0, 1, 3, 4]为例:

Index 0 1 2 3
Value 0 1 3 4

missing=4(00)(11)(23)(34)
=(44)(00)(11)(33)2=2

#Python:
class Solution:
    def missingNumber(self, nums):
        missing = len(nums)
        for i, num in enumerate(nums):
            missing ^= i ^ num
        return missing
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页