二分查找题总结
hot100
搜索插入位置
题目链接:
35.搜索插入位置
代码:
java
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right){
int mid = left + (right - left) / 2;
if (nums[mid] == target){
return mid;
}else if (nums[mid] < target){
left = mid + 1;
}else if (nums[mid] > target){
right = mid - 1;
}
}
return right + 1;
}
}
搜索二维矩阵
题目链接:
74.搜索二维矩阵
代码:
java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int l = 0, r = m*n - 1;
while (l <= r)
{
int mid = l + (r-l)/2;
int row = mid / n;
int col = mid % n;
if (target == matrix[row][col]) return true;
if (target > matrix[row][col]) l = mid + 1;
if (target < matrix[row][col]) r = mid - 1;
}
return false;
}
}
在排序数组中查找元素的第一个和最后一个位置
题目链接:
34.在排序数组中查找元素的第一个和最后一个位置
代码:
java
class Solution {
int binarySearch(int[] nums, int target){
int left = 0, right = nums.length - 1;
while (left <= right){
int mid = left + (right - left) / 2;
if (nums[mid] == target){
return mid;
}else if (nums[mid] > target){
right = mid - 1;
}else if (nums[mid] < target){
left = mid + 1;
}
}
return -1;
}
public int[] searchRange(int[] nums, int target) {
int index = binarySearch(nums,target);
if (index == -1){
return new int[]{-1,-1};
}
int left = index;
int right = index;
while(left - 1 >= 0 && nums[left] == nums[left - 1]){
left --;
}
while(right + 1 < nums.length && nums[right] == nums[right + 1]){
right ++;
}
return new int[]{left,right};
}
}
搜索旋转排序数组
题目链接:
33.搜索旋转排序数组
代码:
java
class Solution {
public int search(int[] nums, int target) {
int n = nums.length;
if (n == 0) return -1;
if (n == 1) return nums[0] == target ? 0:-1;
int l = 0, r = n - 1;
while (l <= r)
{
int mid = l + (r - l) / 2;
if (target == nums[mid]) return mid;
if (nums[0] <= nums[mid])
{
if (nums[0] <= target && target < nums[mid])
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
else
{
if (nums[mid] < target && target <= nums[n - 1])
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
}
return -1;
}
}
寻找旋转排序数组中的最小值
题目链接:
153.寻找旋转排序数组中的最小值
代码:
java
class Solution {
public int findMin(int[] nums) {
int l = 0, r = nums.length - 1;
int minn = Integer.MAX_VALUE;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] < nums[r]) {
minn = Math.min(minn, nums[mid]);
r = mid - 1;
}else {
minn = Math.min(minn, nums[l]);
l = mid + 1;
}
}
return minn;
}
}
寻找两个正序数组的中位数
题目链接:
4.寻找两个正序数组的中位数
代码:
java
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
int len = m + n;
int left = -1, right = -1;
int aStart = 0, bStart = 0;
for (int i = 0; i <= len / 2; i ++)
{
left = right;
if (aStart < m && (bStart >= n || nums1[aStart] < nums2[bStart]))
{
right = nums1[aStart ++];
}
else
{
right = nums2[bStart ++];
}
}
if (len % 2 == 0)
{
return (left + right) / 2.0;
}
else
{
return right;
}
}
}