File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
0033-search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments