1、 Title
LeetCode-704. Binary search
Link:https://leetcode-cn.com/problems/binary-search/
Difficulty: simple
Given an N-element ordered (ascending) integer array nums and a target value target, write a function to search the target in nums. If the target value exists, return the subscript, otherwise return – 1.
Example 1:
Input: num = [- 1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 appears in nums and the subscript is 4
Example 2:
Input: num = [- 1,0,3,5,9,12], target = 2
Output: - 1
Explanation: 2 does not exist in nums, so - 1 is returned
Tips:
You can assume that all elements in nums are not repeated.
N will be between [1, 10000].
Each element of num will be between [- 9999, 9999].
2、 Problem solving ideas
Binary search is an algorithm based on comparing the target value with the middle element of the array.
- If the target value is equal to the intermediate element, the target value is found.
- If the target value is small, continue to search on the left.
- If the target value is large, continue searching on the right.
3、 Implementation process
c++
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0,right = nums.size() - 1,mid;
while(left <= right){
mid =(left+right)/2;
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
right = mid - 1;
}else{
left = mid + 1;
}
}
return -1;
}
};
PHP
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer
*/
function search($nums, $target) {
$left = 0;
$right = count($nums) - 1;
while($left <= $right){
$mid =(int)(($left+$right)/2);
if($nums[$mid] == $target){
return $mid;
}else if($nums[$mid] > $target){
$right = $mid - 1;
}else{
$left = $mid + 1;
}
}
return -1;
}
}
JavaScript
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let left = 0,right = nums.length - 1,mid;
while(left <= right){
mid = Math.floor((left+right)/2);
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
right = mid - 1;
}else{
left = mid + 1;
}
}
return -1;
};
4、 Summary
The time complexity of binary search is O (logn) and the space complexity is O (1).
Basic difficulty
- 69. Square root of X
- 852. Peak index of mountain range array
- 374. Guess the size of the number
- 367. Effective complete square