LeetCode #34 Search for a Range

LeetCode #34 Search for a Range

Question

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Solution

Approach #1

class Solution {
    func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
        let index = searchNumber(nums, target, 0, nums.count - 1)
        if index < 0 {
            return [-1, -1]
        }
        var l = searchNumber(nums, target, 0, index)
        while l >= 0 {
           let t = searchNumber(nums, target, 0, l - 1)
           if t < 0 {
               break
           }
           l = t
        }
        var h = searchNumber(nums, target, index, nums.count - 1)
        while h >= 0 {
           let t = searchNumber(nums, target, h + 1, nums.count - 1) 
           if t < 0 {
               break
           }
           h = t
        }
        return [l, h]
    }
    
    func searchNumber(_ nums: [Int], _ target: Int, _ low: Int, _ high: Int) -> Int {
        var l = low
        var h = high
        var m = 0
        while l <= h {
            m = l + (h - l) / 2
            if target < nums[m] {
                h = m - 1
            } else if target > nums[m] {
                l = m + 1
            } else {
                return m
            }
        }
        return -1
    }
}

Time complexity: O(log(n)).

Space complexity: O(1).

Approach #2

class Solution {
    func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
        var result: [Int] = [-1, -1]
        if nums.isEmpty { return result }
        var l = 0
        var h = nums.count - 1
        while l < h {
            let m = l + (h - l) / 2
            if target > nums[m] {
                l = m + 1
            } else if target < nums[m] {
                h = m - 1
            } else {
                h = m
            }
        }
        if nums[l] != target { return result }
        result[0] = l
        h = nums.count - 1
        while l < h {
            let m = l + (h - l) / 2 + 1
            if target < nums[m] {
                h = m - 1
            } else if target > nums[m] {
                l = m + 1
            } else {
                l = m
            }
        }
        result[1] = l
        return result
    }
}

Time complexity: O(log(n)).

Space complexity: O(1).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7067307.html

转载于:https://www.cnblogs.com/silence-cnblogs/p/7067307.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值