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,包含从0~n中的n个数,问哪个数不存在?
思路:加减就可以了。
public int missingNumber(int[] nums) {
if(nums==null||nums.length==0){
return 0;
}
int res = 0;
for(int i=0;i<nums.length;i++){
res+=nums[i];
res-=i+1;
}
return -res;
}