2024/9/11 LeetCode Hot100 binarySearch

This commit is contained in:
Cool 2024-09-14 19:04:49 +08:00
parent ba931c03be
commit cbe6b62fa7
1 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,43 @@
package com.cool.hot100.binary_search;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/14/17:32
* DayNumber 1
* Hard 2
* Level 5
*/
public class Num33 {
public int search(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
if (nums.length == 1) {
return nums[0] == target ? 0 : -1;
}
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid]==target){
return mid;
}
if(nums[0]<=nums[mid]){
if(nums[0]<=target&&target<nums[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else{
if(nums[nums.length-1]>=target&&target>nums[mid]){
left=mid+1;
}else{
right=mid-1;
}
}
}
return -1;
}
}