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?
思路:在没有元素缺失的情况下,数组下标值+1之和与数组元素之和的差为n,当有元素x缺失时,这个差变为x,因此只需要计算数组下标值+1的和与数组元素之和的差值即可
public class Solution {
public int missingNumber(int[] nums) {
int result = 0;
for(int i=0; i<nums.length; i++){
result = result + i+1 - nums[i];
}
return result;
}
}