knakul853

Untitled

Jun 26th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int search(vector<int>& nums, int target) {
  4.        
  5.         int n = (int)nums.size();
  6.          if(n == 0) return -1;
  7.         // find the smallest number.
  8.        
  9.         int l = 0, h = n-1;
  10.        
  11.         while( l < h )
  12.         {
  13.             int mid = (l + ( h -l )/2);
  14.             if(nums[mid] >nums[h]) l = mid + 1;
  15.             else h = mid;
  16.         }
  17.        
  18.         // faltten the array and use usual binary search.
  19.        int root = l;
  20.         cout<<nums[l]<<"\n";
  21.         l=0, h=n-1;
  22.        
  23.         while(l <= h)
  24.         {
  25.             int mid = (l + (h - l)/2);
  26.            int midr = mid + root;
  27.             midr = midr % n;
  28.            
  29.             if(nums[midr] == target) return midr;
  30.             if(nums[midr] > target) h = mid - 1;
  31.             else l = mid + 1;
  32.         }
  33.        
  34.         return -1;
  35.        
  36.     }
  37. };
Add Comment
Please, Sign In to add comment