Missing Number
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
Example 2:
Input: nums = [0,1] Output: 2
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8
Solution Code
class Solution {
public:
int missingNumber(vector& nums) {
int n = nums.size();
int total_sum = n * (n + 1) / 2;
int array_sum = accumulate(nums.begin(), nums.end(), 0);
return total_sum - array_sum;
}
};
Solution Explanation
The problem requires finding the missing number in an array of distinct numbers ranging from 0 to n. The solution uses the sum formula as follows:
- Sum Formula: The sum of the first n natural numbers is given by the formula
n * (n + 1) / 2
. - Array Sum: Calculate the sum of the elements in the array.
- Missing Number: Subtract the sum of the array from the total sum to get the missing number.