Skip to content

Commit b6dca50

Browse files
committed
Time: 183 ms (21.05%), Space: 37.4 MB (22.25%) - LeetHub
1 parent 42dc73f commit b6dca50

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
fun search(nums: IntArray, target: Int): Int {
3+
val first = nums.first()
4+
val last = nums.last()
5+
6+
if (first <= last) {
7+
return nums.binarySearch(target).coerceAtLeast(-1)
8+
}
9+
if (target in (last + 1) until first) {
10+
return -1
11+
}
12+
13+
val shouldFindLeft = target > last
14+
15+
var low = 0
16+
var high = nums.lastIndex
17+
18+
while (low <= high) {
19+
val mid = (low + high) ushr 1
20+
val midVal: Int = nums[mid]
21+
22+
if (!shouldFindLeft && midVal > last) {
23+
low = mid + 1
24+
} else if (shouldFindLeft && midVal < first) {
25+
high = mid - 1
26+
} else if (midVal < target) {
27+
low = mid + 1
28+
} else if (midVal > target) {
29+
high = mid - 1
30+
} else return mid
31+
}
32+
33+
return -1
34+
}
35+
}

0 commit comments

Comments
 (0)