力扣704 - Binary Search 二分查找
程序员文章站
2022-03-09 15:24:32
...
力扣704 - Binary Search 二分查找
题目描述
Given an array of integers
nums
which is sorted in ascending order, and an integertarget
, write a function to searchtarget
innums
. Iftarget
exists, then return its index. Otherwise, return-1
.Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1
典型的二分查找题, 需要注意的是区间问题和边界值
代码
- 最简单但是效率差的python解法:
class Solution:
def search(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
return -1
- 因为最近在学java,就用java解题了。
正确的二分查找算法:
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length -1;
while (left <= right){
int mid = (left + right)/2;
// found
if (nums[mid] == target){
return mid;
}
//中间比target小,往右搜
else if (nums[mid] < target)
left = mid + 1; //注意区间问题
else if (nums[mid] >= target)
right = mid -1 ;
}
//没找到
return -1;
}
}
推荐阅读
-
二分查找(binary search)java实现及时间复杂度
-
【Binary Search】二分查找(普通二分查找;重复元素返回第一个索引的二分查找;查找范围为2次幂的二分查找)
-
二分查找:力扣4. 寻找两个正序数组的中位数
-
力扣69. x 的平方根(二分查找、牛顿法)
-
二分查找函数:binary_search(arr[],arr[]+size , indx)
-
二分查找(binary search)java实现及时间复杂度
-
4.简单算法python实现:二分查找binary_search
-
【算法题常见解题模式(套路)】Binary Search (二分查找,二分法)
-
力扣704 - Binary Search 二分查找
-
【力扣日记】704 标准二分查找