-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0704-Binary_Search.cpp
More file actions
104 lines (95 loc) · 2.23 KB
/
0704-Binary_Search.cpp
File metadata and controls
104 lines (95 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*******************************************************************************
* 0704-Binary_Search.cpp
* Billy.Ljm
* 01 Apr 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/binary-search/
* Given an array of integers nums which is sorted in ascending order, and an
* integer target, write a function to search target in nums. If target exists,
* then return its index. Otherwise, return -1. You must write an algorithm with
* O(log n) runtime complexity.
*
* ===========
* My Approach
* ===========
* Yup, its textbook binary search.
*
* It has a time complexity of O(log n) and a space complexity of O(1), where n
* is the length of the array being searched
******************************************************************************/
#include <iostream>
#include <vector>
class Solution {
public:
/**
* Binary search algorithm
*
* @param nums array of integers to search in, sorted in ascending order
* @param target integer to search for
*
* @return index of target in nums, or -1 if target is not in nums
*/
int search(std::vector<int>& nums, int target) {
// search range indices
size_t min = 0;
size_t max = nums.size() - 1;
size_t mid;
// binary search
while (max - min > 1) {
mid = (min + max) / 2;
if (nums[mid] > target) {
max = mid;
}
else if (nums[mid] < target) {
min = mid;
}
else { // nums[mid] == target
return int(mid);
}
}
// check last indices
if (nums[min] == target) {
return int(min);
}
else if (nums[max] == target) {
return int(max);
}
else {
return -1;
}
}
};
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (int i = 0; i < v.size(); i++) {
os << v[i] << ",";
}
os << "\b]";
return os;
}
/**
* Test cases
*/
int main(void) {
Solution sol;
std::vector<int> nums;
int target;
// test case 1
nums = { -1,0,3,5,9,12 };
target = 9;
std::cout << "search(" << nums << ", " << target << ") = "
<< sol.search(nums, target) << std::endl;
// test case 2
nums = { -1,0,3,5,9,12 };
target = 2;
std::cout << "search(" << nums << ", " << target << ") = "
<< sol.search(nums, target) << std::endl;
return 0;
}