-
Description Given an array of
n
distinct integers in the range[0, n]
, find the missing integer.Code using namespace std; int missingNumber(vector<int> nums) { return (nums.size() * (nums.size() + 1))/2 - accumulate(nums.begin(), nums.end(), 0); }
Test Cases int missingNumber(std::vector<int> nums); Test(findMissingNumber, should_return_5_for_given_array) { std::vector<int> arr{0, 1, 2, 3, 4, 6, 7, 8, 9, 10}; cr_assert_eq(missingNumber(arr), 5); } Test(findMissingNumber, should_return_2_for_given_array) { std::vector<int> arr{0, 1, 3, 4, 5}; cr_assert_eq(missingNumber(arr), 2); }
Output:
-
Code - #include <vector>
#include <algorithm>- #include <numeric>
- using namespace std;
- int missingNumber(vector<int> nums) {
nums.push_back(nums.size());for (int i = 0; i < static_cast<int>(nums.size()); i++) {if (find(nums.begin(), nums.end(), i) == nums.end()) return i;}return nums.size() - 1;- return (nums.size() * (nums.size() + 1))/2 - accumulate(nums.begin(), nums.end(), 0);
- }
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}