Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

33. Search in Rotated Sorted Array

Posted on 2020-06-28 | Edited on 2021-01-22

LeetCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int search(int[] nums, int target) {
if(nums.length==0) return -1;

int lo=0,hi=nums.length-1;
while(lo<hi){
int mid=(lo+hi)/2;
if(nums[mid]>nums[hi]) lo=mid+1;
else hi=mid;
}
int pivot=lo;
if(target>nums[nums.length-1]) return binary_search(0,pivot-1,nums, target);
return binary_search(pivot,nums.length-1,nums,target);
}
public int binary_search(int lo,int hi,int[] nums, int target){
int mid;
while(lo<=hi){
mid=(lo+hi)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<target) lo=mid+1;
else hi=mid-1;
}
return -1;
}
}
<1…135136137…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%