-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path33-SearchInRotatedSortedArray.kt
74 lines (60 loc) · 1.85 KB
/
33-SearchInRotatedSortedArray.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* 33. Search in Rotated Sorted Array
* https://leetcode.com/problems/search-in-rotated-sorted-array/
*/
class Solution {
fun search(nums: IntArray, target: Int): Int {
val pivotIndex = searchPivot(nums, 0, nums.size - 1)
if (pivotIndex == -1) {
return binarySearch(nums, target, 0, nums.size - 1)
} else {
if(nums[pivotIndex] == target) {
return pivotIndex
}
if (target <= nums[nums.size - 1]) {
return binarySearch(nums, target, pivotIndex, nums.size - 1)
}
return binarySearch(nums, target, 0, pivotIndex - 1)
}
}
/**
* Searches for the pivot position
* O(log n)
*/
fun searchPivot(nums: IntArray, begin: Int, end: Int): Int {
var begin = begin
var end = end
while (begin < end) {
val mid = begin + (end - begin) / 2
if (mid > begin && nums[mid-1] > nums[mid]) {
return mid
} else if (mid < end && nums[mid+1] < nums[mid]) {
return mid + 1
} else {
if (nums[begin] >= nums[mid]) {
end = mid -1
} else {
begin = mid + 1
}
}
}
return -1
}
fun binarySearch(nums: IntArray, target: Int, begin: Int, end: Int): Int {
var begin = begin
var end = end
while (begin <= end) {
val mid = begin + (end - begin) / 2
println("mid "+mid)
if (target == nums[mid]) {
return mid
}
if (target > nums[mid]) {
begin = mid + 1
} else {
end = mid - 1
}
}
return -1
}
}