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

posted on 2017-06-24 09:01  Silence_cnblogs  阅读(292)  评论(0编辑  收藏  举报