Skip to content

Commit

Permalink
Create: 0034-find-first-and-last-position-of-element-in-sorted-array.…
Browse files Browse the repository at this point in the history
…swift
  • Loading branch information
Ykhan799 authored Feb 4, 2023
1 parent 3367a45 commit 9646f70
Showing 1 changed file with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
let left = binSearch(nums, target, true)
let right = binSearch(nums, target, false)
return [left, right]
}

func binSearch(_ nums: [Int], _ target: Int, _ leftBias: Bool) -> Int {
var left = 0, right = nums.count - 1
var i = -1
while left <= right {
let mid = (left + right) / 2
if target > nums[mid] {
left = mid + 1
}
else if target < nums[mid] {
right = mid - 1
}
else {
i = mid
if leftBias {
right = mid - 1
}
else {
left = mid + 1
}
}
}
return i
}
}

0 comments on commit 9646f70

Please sign in to comment.