Skip to content

Commit 620f1ae

Browse files
authored
Merge pull request neetcode-gh#2205 from Ykhan799/main
Create: 0034-find-first-and-last-position-of-element-in-sorted-array.swift
2 parents 3367a45 + 9646f70 commit 620f1ae

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
3+
let left = binSearch(nums, target, true)
4+
let right = binSearch(nums, target, false)
5+
return [left, right]
6+
}
7+
8+
func binSearch(_ nums: [Int], _ target: Int, _ leftBias: Bool) -> Int {
9+
var left = 0, right = nums.count - 1
10+
var i = -1
11+
while left <= right {
12+
let mid = (left + right) / 2
13+
if target > nums[mid] {
14+
left = mid + 1
15+
}
16+
else if target < nums[mid] {
17+
right = mid - 1
18+
}
19+
else {
20+
i = mid
21+
if leftBias {
22+
right = mid - 1
23+
}
24+
else {
25+
left = mid + 1
26+
}
27+
}
28+
}
29+
return i
30+
}
31+
}

0 commit comments

Comments
 (0)