-
Notifications
You must be signed in to change notification settings - Fork 20
/
SearchInRotatedSortedArrayII.kt
52 lines (48 loc) · 1.49 KB
/
SearchInRotatedSortedArrayII.kt
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
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Arrays
/**
* Follow up for "Search in Rotated Sorted Array":
* What if duplicates are allowed?
*
* Would this affect the run-time complexity? How and why?
*
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
*
* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
*
* Write nums function to determine if nums given target is in the array.
*
* The array may contain duplicates.
*
* Accepted.
*/
class SearchInRotatedSortedArrayII {
fun search(nums: IntArray, target: Int): Boolean {
if (nums.isEmpty()) {
return false
}
var start = 0
var end = nums.size - 1
while (start <= end) {
val mid = start + (end - start) / 2
if (nums[mid] == target) {
return true
}
if (nums[mid] < nums[end]) { // right half sorted
if (target > nums[mid] && target <= nums[end]) {
return Arrays.binarySearch(nums, mid, end + 1, target) >= 0
} else {
end = mid - 1
}
} else if (nums[mid] > nums[end]) { // left half sorted
if (target >= nums[start] && target < nums[mid]) {
return Arrays.binarySearch(nums, start, mid + 1, target) >= 0
} else {
start = mid + 1
}
} else {
end--
}
}
return false
}
}