Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
思路
- 缺少的数 ==
sum(0.....n) - sum(num[i])
- 有可能input的数组很大,直接计算sum会超过integer的范围,所以一边加i一边减去nums[i]。最后剩下的数就是missing number
class Solution {
public int missingNumber(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int add = 0;
int result = nums.length;
for (int i = 0; i < nums.length; i++) {
//add += i;
result = result + (i - nums[i]);
}
return result;
}
}