题目
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?
十分钟尝试
我的可能思路
1. 排序
2. 利用空间换时间,下标是新数组的位置,看新数组哪个为空,就是缺少哪个
3. 存入map,并找到最大元素(不需要找到最大,因为是有序的,元素的size就是最大值+1),重新遍历map,看每个元素+1,是否存在map中(最大元素除外)
但是这些算法都不同时满足要求:O(n)和常量存储空间
看了一下答案利用高斯公式,求和:
class Solution {
public int missingNumber(int[] nums) {
int expectedSum = nums.length*(nums.length + 1)/2;
int actualSum = 0;
for (int num : nums) actualSum += num;
return expectedSum - actualSum;
}
}