Advertisement
Niloy007

Binary Search

Mar 13th, 2021
996
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.43 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int search(vector<int>& nums, int target) {
  4.         int l = 0, r = nums.size() - 1;
  5.         while (l <= r) {
  6.             int mid = (l + r) / 2;
  7.             if (nums[mid] == target) {
  8.                 return mid;
  9.             }
  10.             if (nums[mid] < target) {
  11.                 l = mid + 1;
  12.             } else {
  13.                 r = mid - 1;
  14.             }
  15.         }
  16.         return -1;
  17.     }
  18. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement