二分查找
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
int mid = 0;
while(left<=right) {
mid = (left+right)>>1;
if(target < nums[mid]) {
right = mid-1;
}else if(target > nums[mid]) {
left = mid+1;
}else {
return mid;
}
}
return -1;
}
}
以二分查找为模板的题目
1. 旋转数组的最小数字
做了很久,很恶心
https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/
class Solution {
public int minArray(int[] numbers) {
int left = 0,right=numbers.length-1;
int mid= 0;
while(left<=right) {
mid = (left+right)>>1;
if(numbers[mid] < numbers[right]) {
right = mid;
} else if (numbers[mid] > numbers[right]) {
left = mid+1;
} else {
right-=1;
}
}
return numbers[left];
}
}