Skip to content

Commit cf8bbcc

Browse files
authored
Merge pull request #2106 from a93a/main
Create 0034-find-first-and-last-position-of-element-in-sorted-array.kt
2 parents 6b03699 + 90ea69a commit cf8bbcc

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//same solution but with function
2+
class Solution {
3+
fun searchRange(nums: IntArray, target: Int): IntArray {
4+
val res = intArrayOf(-1,-1)
5+
6+
fun binarySearch(getLeft: Boolean): Int{
7+
var left = 0
8+
var right = nums.size-1
9+
var pos = -1
10+
while(left <= right){
11+
val mid = (left + right) / 2
12+
if(target > nums[mid]){
13+
left = mid + 1
14+
}else if(target < nums[mid]){
15+
right = mid - 1
16+
}else{
17+
pos = mid
18+
if(getLeft)
19+
right = mid -1
20+
else
21+
left = mid + 1
22+
}
23+
}
24+
return pos
25+
}
26+
27+
res[0] = binarySearch(true)
28+
res[1] = binarySearch(false)
29+
30+
return res
31+
}
32+
}

0 commit comments

Comments
 (0)