Skip to content

Commit 8641c26

Browse files
committed
feat: search-in-rotated-sorted-array
1 parent 360fe20 commit 8641c26

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">week10-2. search-in-rotated-sorted-array</a>
3+
* <li>Description: nums is sorted in ascending order and is possibly rotated at an unknown pivot index. return the index of target if it is in nums, or -1 </li>
4+
* <li>Topics: Array, Binary Search </li>
5+
* <li>Time Complexity: O(logN), Runtime 1ms </li>
6+
* <li>Space Complexity: O(logN), Memory 43.23MB </li>
7+
*/
8+
class Solution {
9+
public int search(int[] nums, int target) {
10+
if(nums.length==1) {
11+
if(nums[0]==target) return 0;
12+
return -1;
13+
}
14+
15+
Queue<int[]> queue = new LinkedList<>();
16+
queue.add(new int[]{0, nums.length-1});
17+
18+
int pivot = -1;
19+
if(nums[0]<nums[nums.length-1]) {
20+
pivot=nums.length-1;
21+
}
22+
23+
while(pivot==-1 && !queue.isEmpty()){
24+
int[] q = queue.poll();
25+
int mid = (q[0]+q[1])/2;
26+
if(mid+1 > nums.length-1) {
27+
continue;
28+
}
29+
if(nums[mid]>nums[mid+1]) {
30+
pivot=mid;
31+
break;
32+
}
33+
queue.add(new int[]{q[0], mid});
34+
queue.add(new int[]{mid+1, q[1]});
35+
}
36+
37+
int left = 0, right = nums.length-1;
38+
if(target>=nums[0] && target<=nums[pivot]) {
39+
right = pivot;
40+
} else {
41+
left = pivot+1;
42+
}
43+
44+
45+
while(left<=right){
46+
int mid = (left+right)/2;
47+
if(target < nums[mid]) {
48+
right=mid-1;
49+
} else {
50+
left=mid+1;
51+
}
52+
}
53+
54+
if(nums[right] == target) {
55+
return right;
56+
}
57+
58+
return -1;
59+
}
60+
}

0 commit comments

Comments
 (0)