给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
链接:https://leetcode-cn.com/problems/binary-search
class Solution {
public int search(int[] nums, int target) {
int len = nums.length;
int head = 0;
int tail = len - 1;
int index = (head + tail) / 2;
while (true) {
if (target == nums[index]) {
return index;
} else if (head==tail) {
return -1;
} else if (target > nums[index]) {
if(index==tail){
return -1;
}
head = index + 1;
index = (tail + head) / 2;
} else {
if(index==head){
return -1;
}
tail = index - 1;
index = (head + tail) / 2;
}
}
}
}
这个题刚开始思路有点乱,反映到代码也有点乱。二分查找确实是一看就会,一写就废,划分边界需要仔细一点。