Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
数组nums有范围在[0, n]的不同的n个数字,返回丢失的那个数字。
思路:
解读一下题目,[0, n]范围的数字一共应该是n+1个,而nums中只有n个不同的数字,少了一个。
而我们知道0~n的数字的和应该是(0+n) * (n-1) / 2
然后一一减去nums中的数字,剩下的那个就是丢失的数字。
public int missingNumber(int[] nums) {
int n = nums.length;
int res = n * (n+1) / 2;
for(int i = 0; i < n; i++) {
res -= nums[i];
}
return res;
}