Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.html
Your algorithm's runtime complexity must be in the order of O(log n).swift
If the target is not found in the array, return [-1, -1]
.app
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.code
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)).htm
Space complexity: O(1).blog
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)).leetcode
Space complexity: O(1).get
轉載請註明出處:http://www.cnblogs.com/silence-cnblogs/p/7067307.htmlit