问题链接:https://leetcode.com/problems/missing-number/
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?
但是效率太低且空间复杂度为线性。
运用n个数的累加和的方式完成。时间常数,空间线性
public class Solution {
public int missingNumber(int[] nums) {
if(nums==null || nums.length==0)
return 0;
int len = nums.length;
int sum = len*(len+1)/2;
for(int i=0;i<len;i++) {
sum-=nums[i];
}
return sum;
}
}