LeetCode 704. Binary Search
考点 | 难度 |
---|---|
Binary Search | Easy |
题目
Given an array of integers nums
which is sorted in ascending order, and an integer target, write a function to search target
in nums
. If target exists, then return its index. Otherwise, return -1
.
You must write an algorithm with O(log n) runtime complexity.
思路
因为array是从小到大排序,用普通的binary search就可以。
答案
public int search(int[] nums, int target) {
int pivot, left = 0, right = nums.length - 1;
while (left <= right) {
pivot = left + (right - left) / 2;
if (nums[pivot] == target) return pivot;
if (target < nums[pivot]) right = pivot - 1;
else left = pivot + 1;
}
return -1;
}