Table of contents
1. Question analysis
Question link: 704. Binary search - LeetCode
The question is very simple, just find a target.
2. Algorithm principle
According to the most basic binary search algorithm:
In an ordered array, the left and right boundaries are left and right respectively, and the value of the position pointed by mid is x.
1. x < target,left = mid + 1
2. x > target,right = mid - 1
3. x == target, just return the result·
3. Code writing
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] < target) left = mid + 1;
else if(nums[mid] > target) right = mid - 1;
else if(nums[mid] == target) return mid;
}
return -1;
}
};
4. The first bisection template
This is our first template~
while (left <= right) {
int mid = left + (right - left) / 2;
if ( ... ) left = mid + 1;
else if ( ... ) right = mid - 1;
else if ( ... ) return mid;
}
Write at the end:
That’s the content of this article, thank you for reading.
If you feel you have gained something, you can give the blogger a like .
If there are omissions or errors in the content of the article, please send a private message to the blogger or point it out in the comment area~