2024/11/10 灵茶题单 二分查找

This commit is contained in:
Cool 2024-11-10 17:12:02 +08:00
parent c2a1123a7e
commit d2ad6fb2c4
2 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package com.cool.ling_cha_mount.binary_search;
/**
* @author : Cool
* @date: 2024/11/08
* 34. 在排序数组中查找元素的第一个和最后一个位置
*/
public class Num34 {
public int[] searchRange(int[] nums, int target) {
int start = binarySearch(nums, target);
if (start < nums.length && nums[start] == target) {
int end = binarySearch(nums, target + 1) - 1;
return new int[]{start, end};
}
return new int[]{-1, -1};
}
public int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (right - left) / 2 + left;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}

View File

@ -0,0 +1,24 @@
package com.cool.ling_cha_mount.binary_search;
/**
* @author : Cool
* @date: 2024/11/10
* 704. 二分查找
*/
public class Num704 {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (right - left) / 2 + left;
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
}