forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch in Rotated Sorted Array II.java
39 lines (33 loc) · 1.04 KB
/
Search in Rotated Sorted Array II.java
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public boolean search(int[] nums, int target) {
if (nums == null || nums.length == 0) return false;
int left = 0, right = nums.length-1;
int start = 0;
//1. find index of the smallest element
while(left < right) {
while (left < right && nums[left] == nums[left + 1])
++left;
while (left < right && nums[right] == nums[right - 1])
--right;
int mid = left + (right-left)/2;
if (nums[mid] > nums[right]) {
left = mid +1;
} else right = mid;
}
//2. figure out in which side our target lies
start = left;
left = 0;
right = nums.length-1;
if (target >= nums[start] && target <= nums[right])
left = start;
else right = start;
//3. Run normal binary search in sorted half.
while(left <= right) {
int mid = left + (right - left)/2;
if (nums[mid] == target) return true;
if (nums[mid] > target) right = mid-1;
else left = mid + 1;
}
return false;
}
}