forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create: 0034-find-first-and-last-position-of-element-in-sorted-array.…
…swift
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
swift/0034-find-first-and-last-position-of-element-in-sorted-array.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |