May 06, 2020
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
func searchRange(nums []int, target int) []int {
if len(nums) == 0 {
return []int{-1,-1}
}
if len(nums) == 1 {
if nums[0] == target {
return []int{0,0}
}
return []int{-1,-1}
}
start := nums[0]
end := nums[len(nums) - 1]
if target < start {
return []int{-1,-1}
} else if target > end {
return []int{-1,-1}
}
midIndex := len(nums) / 2
middle := nums[midIndex]
if middle < target {
res := searchRange(nums[midIndex:], target)
if res[0] == -1 {
return res
}
return []int{res[0] + midIndex, res[1] + midIndex}
} else if middle > target {
res := searchRange(nums[:midIndex], target)
return res
} else {
l := searchRange(nums[:midIndex], target)
r := searchRange(nums[midIndex:], target)
if l[0] == -1 {
return []int{r[0] + midIndex, r[1] + midIndex}
} else {
return []int{l[0], r[1] + midIndex}
}
}
}
题目中一看到时间复杂度要求为 O(logn),就会立马想到使用二分法求解。我这里通过递归的方式不断折半来定位到要查找的元素。
痕迹
没有过去,就没法认定现在的自己