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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
解题思路:这道题目的意思是要找出缺失的那一个值,这里直接就是求和,然后对数组进行减就可以找到缺失的哪个值。
public class Solution {
public int missingNumber(int[] nums) {
int len = nums.length;
if(len == 0)
{
return 0;
}
int sum = ((len+1)*len) / 2;
for(int i = 0; i < len; i++)
{
sum -= nums[i];
}
return sum;
}
}