Skip to content

Commit be7346b

Browse files
committed
Binary Search
1 parent 7d63ed8 commit be7346b

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
二分法,假设当期区间为[lhs,rhs),如果nums[lhs] < nums[rhs-1],说明是单调的,就返回nums[lhs]
3+
否则说明不是单调的,就继续二分搜索[lhs,rhs)
4+
由于多了相等的情况,每次搜索不一定能减去一半的区间
5+
所以平均复杂度是O(logn)的,最坏复杂度是O(n)的
6+
7+
*/
8+
class Solution {
9+
public:
10+
int findMin(vector<int> &nums) {
11+
return solve(nums,0,nums.size());
12+
}
13+
int solve(vector<int> &nums,int lhs,int rhs)
14+
{
15+
if(rhs - lhs == 1) return nums[lhs];
16+
else{
17+
if(nums[lhs] < nums[rhs-1]) return nums[lhs];
18+
else{
19+
return min(solve(nums,lhs,(lhs + rhs) / 2),solve(nums,(lhs + rhs) / 2,rhs));
20+
}
21+
}
22+
}
23+
};
24+
25+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
二分法,假设当期区间为[lhs,rhs),如果nums[lhs] < nums[rhs-1],说明是单调的,就返回nums[lhs]
3+
否则说明不是单调的,就继续二分搜索[lhs,rhs)
4+
最后的时间复杂度是O(logn)的
5+
6+
*/
7+
class Solution {
8+
public:
9+
int findMin(vector<int> &nums) {
10+
return solve(nums,0,nums.size());
11+
}
12+
int solve(vector<int> &nums,int lhs,int rhs)
13+
{
14+
if(rhs - lhs == 1) return nums[lhs];
15+
else{
16+
if(nums[lhs] < nums[rhs-1]) return nums[lhs];
17+
else{
18+
return min(solve(nums,lhs,(lhs + rhs) / 2),solve(nums,(lhs + rhs) / 2,rhs));
19+
}
20+
}
21+
}
22+
};
23+

0 commit comments

Comments
 (0)