LeetCode Note Java 00704: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.

我的解法

標準的二元搜尋法,設定左右兩邊界,每次測試兩邊界正中間的索引,是答案就回傳該索引,不是就修正邊界。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int middle = (left + right) / 2;
int value = nums[middle];
if (value == target) {
return middle;
}
if (value < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
}