q1:二分查找
二分查找的思想:对于有序数组且无重复元素,通过条件判断不断缩小可能答案的区间,直到找到答案或者没有找到答案
常规二分防溢出写法:
class BinarySearch {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] == target) return mid;
else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}
二分变式:在常规的基础上面,查找有重复元素的最左边界索引
思想:对于有序数组,通过条件判断不断缩小可能答案的区间,直到缩小到区间为1,则最可能为答案的数值在此区间内
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left] == target ? left : -1;
}
}
二分变式:在常规的基础上面,查找有重复元素的最右边界索引
思想:对于有序数组,通过条件判断不断缩小可能答案的区间,直到缩小到区间为1,则最可能为答案的数值在此区间内
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + ((right - left) >> 1) + 1;
if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid;
}
}
return nums[right] == target ? right : -1;
}
}