Advertisement
nikunjsoni

1060

May 15th, 2021
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int missingElement(vector<int>& nums, int k) {
  4.         int n = nums.size();
  5.         // If k > last element of array.
  6.         if(k > countMissing(nums, n-1)){
  7.             return nums[n-1] + k - countMissing(nums, n-1);
  8.         }
  9.        
  10.         // Binary Search the range and find lower bound where missing nums >= k.
  11.         int l = 0, r = n-1;
  12.         while(l < r){
  13.             int mid = (l+r)/2;
  14.             if(countMissing(nums, mid) < k)
  15.                 l = mid+1;
  16.             else r = mid;
  17.         }
  18.         return nums[l-1] + k - countMissing(nums, l-1);
  19.     }
  20.    
  21.     int countMissing(vector<int> &nums, int idx){
  22.         return nums[idx] - nums[0] - idx;
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement