LeetCode – 34. Find First and Last Position of Element in Sorted Array

題目連結: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

//Test cases:
//nums: [], target = 3             ,output: [-1, -1]
//nums: [1,2,3], target = 3        ,output: [2, 2]
//nums: [1,2,3,3,3,4], target = 3  ,output: [2, 4]
//nums: [1,2,3,3,4], target = 3    ,output: [2, 3]
//nums: [3,3,3], target = 3        ,output: [0, 2]
func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
    if nums.count == 0 { return [-1, -1] }
    var left = 0
    var right = nums.count - 1
    var targetIndex = -1
    while left <= right {
        let mid = (left + right) / 2
        if nums[mid] == target {
            targetIndex = mid
            break
        } else if nums[mid] < target {
            left = mid + 1
        } else {
            right = mid - 1
        }
    }

    if targetIndex == -1{
        return [-1, -1]
    } else {
        var left = targetIndex
        var right = targetIndex
        while (left - 1) >= 0 && nums[left - 1] == nums[targetIndex] {
            left -= 1
        }
        while (right + 1) < nums.count && nums[right + 1] == nums[targetIndex] {
            right += 1
        }
        return [left, right]
    }
}