题目:给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果目标值存在返回下标,否则返回 -1
。
解法一:
没有用二分查找
class Solution {
public int search(int[] nums, int target) {
for(int i = 0; i < nums.length;i++){
if (nums[i] == target){
return i;
}
}
return -1;
}
}
写二分法,区间的定义一般为两种,左闭右闭即[left, right],或者左闭右开即[left, right)。
解法二:
二分查找【左闭右闭区间】
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int middle;
while(left <= right){
middle = left + (right - left)/2;
if (nums[middle] > target){
right = middle -1;
}else if(nums[middle] < target){
left = middle +1;
}else{
return middle;
}
}
return -1;
}
}
解法三:
二分查找【左闭右开区间】
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length;
int middle;
while(left < right){
middle = left + (right - left)/2;
if (nums[middle] > target){
right = middle;
}else if(nums[middle] < target){
left = middle + 1;
}else if(nums[middle] == target){
return middle;
}
}
return -1;
}
}