利用二分查找找出给定元素在数组中的位置,没有则返回-1
class Solution {
public int search(int[] nums, int target) {
int length = nums.length; //数组总长度
int first = 0; //数组开始下标
int index = 0; //目标索引,初始化0
while(first != length){
index = (first + length - 1) / 2;
if(target == nums[index]){
return index;
}else if(target > nums[index]){
first = index + 1;
}else{
length = index;
}
}
return -1;
}
}