704.二分查找Java
题目描述
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
输入输出样式
示例1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
本题来自LeetCode:https://leetcode-cn.com/problems/binary-search/
思路
二分查找即每次都将当前数组的中点与目标target比较,如果相等即为所寻找的目标;如果不等,那么当前数组会被折半,继续对折半后的数组的中点与target比较,如此往复。
算法分析
时间复杂度O(log n),空间复杂度为O(1)
求解函数
public int search(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low <= high) {
//当前数组中点
int mid = (low + high) / 2;
if (nums[mid] == target) return mid;
//中点小于目标值,则说明目标值在右边一半的数组中
//则需要将中点右边作为新折半数组的起点low
if (nums[mid] < target) low = mid + 1;
//同上理,将中点左边作为新折半数组的终点high
else high = mid - 1;
}
return -1;
}