Skip to content

Commit 14b54f9

Browse files
[CPP] 704. Binary Search
1 parent 95475aa commit 14b54f9

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

cpp/704-Binary-Search.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
int search(vector<int>& nums, int target) {
4+
int n = nums.size();
5+
if (nums[0] == target) return 0;
6+
if (nums[n-1] == target) return n-1;
7+
8+
int start = 0, end = n-1;
9+
10+
while (start < end) {
11+
int mid = start + (end-start)/2;
12+
if (nums[mid] == target) return mid;
13+
if (nums[mid] > target) {
14+
end = mid;
15+
}
16+
else {
17+
start = mid + 1;
18+
}
19+
}
20+
21+
return -1;
22+
}
23+
};

0 commit comments

Comments
 (0)