268. Missing Number 丢失的数字

@TOC

# 题目描述

Given an array containing `n` distinct numbers taken from `0, 1, 2, ..., n`, find the one that is missing from the array.

Example 1:

``````Input: [3,0,1]
Output: 2
``````

Example 2:

``````Input: [9,6,4,2,3,5,7,0,1]
Output: 8
``````

Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

# 解题方法

# 求和

``````public class Solution {
public int missingNumber(int[] nums) {
int sum = 0;
int len = nums.length;
for(int i = 0; i < len; i++){
sum += nums[i];
}
return len * (len + 1)/2 - sum;
}
}
``````

``````class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
num_sum = sum(nums)
return n * (n + 1) / 2 - num_sum
``````

# 异或

``````public int missingNumber(int[] nums) { //xor
int res = nums.length;
for(int i=0; i<nums.length; i++){
res ^= i;
res ^= nums[i];
}
return res;
}
``````

# 日期

2017 年 4 月 21 日 2018 年 11 月 16 日 —— 又到周五了！