Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
0
到 size(nums)
和,再减去数组中所有元素即为结果class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = size(nums);
n = n * (n + 1) / 2;
return accumulate(begin(nums), end(nums), n, minus<int>{});
}
};
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = size(nums);
for (int i = 0; i < size(nums); ++i) {
res += i - nums[i];
}
return res;
}
};