2024/9/13 Hot100 二分查找

This commit is contained in:
linlihong 2024-09-13 17:25:28 +08:00
parent dde55bb39b
commit ba931c03be
2 changed files with 86 additions and 0 deletions
src/main/java/com/cool/hot100/binary_search

View File

@ -0,0 +1,44 @@
package com.cool.hot100.binary_search;
import org.junit.Test;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/13/16:02
* DayNumber 4
* Hard 2
* Level ?
*/
public class Num34 {
public int[] searchRange(int[] nums, int target) {
int index = binarySearch(nums, target);
if(index==nums.length||nums[index]!=target){
return new int[]{-1,-1};
}
int end=binarySearch(nums,target+1)-1;
return new int[]{index,end};
}
private int binarySearch(int[] nums, int target) {
int left=0;
int right=nums.length-1;
while (left <= right) {
int mid =left+(right-left)/2;
if(target>nums[mid]){
left=mid+1;
}else{
right=mid-1;
}
}
return left;
}
@Test
public void test() {
searchRange(new int[]{5,7,7,8,8,10}, 6);
}
}

View File

@ -0,0 +1,42 @@
package com.cool.hot100.binary_search;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/13/15:35
* DayNumber 3
* Hard 2
* Level ?
*/
public class Num74 {
public boolean searchMatrix(int[][] matrix, int target) {
int rowLen=matrix.length;
if(rowLen==0){
return false;
}
int index=0;
int colLen=matrix[0].length;
for(int i=1;i<rowLen;i++){
if(target<matrix[i][0]){
break;
}
index=i;
}
int left=0;
int right=colLen;
while(left<right){
int mid=(left+right)/2;
if(target<matrix[index][mid]){
right=mid;
}else if(target>matrix[index][mid]){
left=mid+1;
}else{
return true;
}
}
return false;
}
}