-
Description Given an array (vector, for C++) of
n
distinct integers in the range[0, n]
, find the one that is missing.First C++ solution; fixed up the test cases that were missing 0 (so those in the parent description wouldn't have worked), reworked to a vector for simplicity (could do the same op on an array + length combo, but it's just less idiomatic), simplified structure for the tests, and finally implemented an actual solution.
Code 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; }
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 class Solution {public:int missingNumber(vector<int>& nums) {}};- #include <vector>
- #include <algorithm>
- 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;
- }
Test Cases - #include <criterion/criterion.h>
// Function to find the missing number in an array of integersint findMissingNumber(int arr[], int n) {// Code to find the missing number}- int missingNumber(std::vector<int> nums);
- Test(findMissingNumber, should_return_5_for_given_array) {
int arr[] = {1, 2, 3, 4, 6, 7, 8, 9, 10};int n = sizeof(arr) / sizeof(arr[0]);cr_assert_eq(findMissingNumber(arr, n), 5);- 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) {
int arr[] = {1, 3, 4, 5};int n = sizeof(arr) / sizeof(arr[0]);cr_assert_eq(findMissingNumber(arr, n), 2);- std::vector<int> arr{0, 1, 3, 4, 5};
- cr_assert_eq(missingNumber(arr), 2);
- }
- 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 }}