Skip to content

Commit

Permalink
[CPP] 704. Binary Search
Browse files Browse the repository at this point in the history
  • Loading branch information
UnresolvedCold committed Apr 3, 2022
1 parent 95475aa commit 14b54f9
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions cpp/704-Binary-Search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
if (nums[0] == target) return 0;
if (nums[n-1] == target) return n-1;

int start = 0, end = n-1;

while (start < end) {
int mid = start + (end-start)/2;
if (nums[mid] == target) return mid;
if (nums[mid] > target) {
end = mid;
}
else {
start = mid + 1;
}
}

return -1;
}
};

0 comments on commit 14b54f9

Please sign in to comment.