File tree 1 file changed +57
-0
lines changed
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ // /
2
+ // / LeetCode
3
+ // / By Reza Ebrahimi <reza.ebrahimi.dev@gmail.com>
4
+ // /
5
+ // / Binary Search Problem
6
+ // / https://leetcode.com/problems/binary-search
7
+ // /
8
+ // / Runtime: 40 ms, faster than 39.64% of C++ online submissions for Binary Search.
9
+ // / Memory Usage: 32 MB, less than 5.31% of C++ online submissions for Binary Search.
10
+ // / Time Submitted: 06/22/2021 00:07
11
+ // /
12
+
13
+ class Solution {
14
+ public:
15
+ int search (vector<int >& nums, int target) {
16
+ return binary_search_ex (move (nums), target, 0 );
17
+ }
18
+
19
+ int binary_search_ex (vector<int > nums, int target, int offset) {
20
+ int ret = -1 ;
21
+ int len = nums.size ();
22
+ int mid = len / 2 ;
23
+
24
+ sort (nums.begin (), nums.end ());
25
+
26
+ if (len <= 0 ) {
27
+ return -1 ;
28
+ } else if (len == 1 && target == nums[mid]) {
29
+ return mid + offset;
30
+ } else if (len == 1 && target != nums[mid]) {
31
+ return -1 ;
32
+ }
33
+
34
+ if (target < nums[mid]) {
35
+ std::vector<int > vec (nums.begin (), nums.begin () + mid);
36
+ ret = binary_search_ex (vec, target, 0 );
37
+ } else if (target > nums[mid]) {
38
+ std::vector<int > vec (nums.begin () + mid, nums.end ());
39
+ ret = binary_search_ex (vec, target, mid);
40
+ } else {
41
+ return mid + offset;
42
+ }
43
+
44
+ len = len - mid;
45
+ mid = len / 2 ;
46
+
47
+ if (mid == 0 && target == nums[mid]) {
48
+ return mid + offset;
49
+ }
50
+
51
+ if (ret == -1 ) {
52
+ return ret;
53
+ }
54
+
55
+ return ret + offset;
56
+ }
57
+ };
You can’t perform that action at this time.
0 commit comments