Skip to content

Commit f6f01ca

Browse files
authored
Create missing-element-in-sorted-array.cpp
1 parent 75ea29a commit f6f01ca

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int missingElement(vector<int>& nums, int k) {
7+
int left = 0, right = nums.size() - 1;
8+
while (left <= right) {
9+
const auto& mid = left + (right - left) / 2;
10+
if (check(nums, k, mid)) {
11+
right = mid - 1;
12+
} else {
13+
left = mid + 1;
14+
}
15+
}
16+
return nums[right] + (k - missingCount(nums, right));
17+
}
18+
19+
private:
20+
int missingCount(const vector<int>& nums, int x) {
21+
return (nums[x] - nums[0] + 1) - (x - 0 + 1);
22+
}
23+
24+
bool check(const vector<int>& nums, int k, int x) {
25+
return k <= missingCount(nums, x);
26+
}
27+
};

0 commit comments

Comments
 (0)