Advertisement
Guest User

Untitled

a guest
Feb 16th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. class Solution {
  2. private:
  3.     int binarySearch(vector<int>& arr, int l, int r, int target)
  4.     {
  5.         if (r >= l) {
  6.             int mid = l + (r - l) / 2;
  7.  
  8.             // If the element is present at the middle
  9.             // itself
  10.             if (arr[mid] == target)
  11.                 return mid;
  12.  
  13.             // If element is smaller than mid, then
  14.             // it can only be present in left subarray
  15.             if (arr[mid] > target)
  16.                 return binarySearch(arr, l, mid - 1, target);
  17.  
  18.             // Else the element can only be present
  19.             // in right subarray
  20.             return binarySearch(arr, mid + 1, r, target);
  21.         }
  22.  
  23.         // We reach here when element is not
  24.         // present in array
  25.         return -1;
  26.     }
  27.    
  28. public:
  29.     vector<int> searchRange(vector<int>& nums, int target) {
  30.         vector<int> returnResult;
  31.         int resultindex = binarySearch(nums, 0, nums.size()-1, target);
  32.         if(resultindex == -1) {
  33.             returnResult.push_back(-1);
  34.             returnResult.push_back(-1);
  35.         } else {
  36.             //now that we have an index of 1 item, search start and end.
  37.             int start=resultindex;
  38.             int end=resultindex;
  39.            
  40.             while(nums[start]==target && start > 0) {
  41.                 start--;                
  42.             }
  43.             if(nums[start] != target) {
  44.                 start++;
  45.             }
  46.            
  47.             while(nums[end]==target && end < nums.size()) {
  48.                 end++;                
  49.             }
  50.             if(nums[end] != target) {
  51.                 end--;
  52.             }
  53.            
  54.             returnResult.push_back(start);
  55.             returnResult.push_back(end);            
  56.         }
  57.        
  58.         return returnResult;
  59.     }
  60. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement