268.MissingNumber
Problem Statement¶
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.
Approach¶
- Calculate Sum
sum = n * (n-1)/2
where n is nums.size()+1- forEach the numbers array and subtract values
- The sum you have at the end is the result
- XOR
- SORT
Detailed Reference -> LeetCode Article
Code¶
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size()+1;
long long sum = n * (n-1)/2;
for(auto a : nums)
sum -= a;
return sum;
}
};