首页 > 编程语言> > 0034-leetcode算法实现之查找元素位置-find-first-and-last-position-of-element-in-sorted-array-python&golang实现
0034-leetcode算法实现之查找元素位置-find-first-and-last-position-of-element-in-sorted-array-python&golang实现
作者:互联网
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
python
class Solution:
def searchRange(self, nums: [int], target: int) -> [int]:
def search(nums: [int], target: int) -> int:
left, right = 0, len(nums)
while left < right:
mid = int((left+right)/2)
if nums[mid] >= target:
right = mid
else:
left = mid + 1
return left
# 找到第一个=target的位置
leftIdx = search(nums, target)
# 找到第一个 > target的位置
rightIdx = search(nums, target+1)
if leftIdx == len(nums) or nums[leftIdx] != target:
return [-1, -1]
return [leftIdx, rightIdx-1]
if __name__ == "__main__":
nums1 = [1,3]
target1 = 2
nums2 = [1,3,3,3,3,3,3,3,5,5,6]
target2 = 5
test = Solution()
print(test.searchRange(nums1,target1)) # [-1, -1]
print(test.searchRange(nums2,target2)) # [8, 9]
golang
func main() {
var nums = []int{1, 3, 3, 3, 3, 3, 3, 3, 5, 5, 6}
var target int = 5
res := searchRange(nums, target)
fmt.Println(res)
}
func searchRange(nums []int, target int) []int {
//第一个=target的位置
leftIdx := search(nums, target)
rightIdx := search(nums, target+1)
if leftIdx == len(nums) || nums[leftIdx] != target {
return []int{-1, -1}
}
return []int{leftIdx, rightIdx - 1}
}
func search(nums []int, target int) int {
var left int = 0
var right int = len(nums)
for left < right {
var mid int = (left + right) / 2
if nums[mid] >= target {
right = mid
} else {
left = mid + 1
}
}
return left
}
标签:right,last,target,nums,int,0034,mid,find,left 来源: https://www.cnblogs.com/davis12/p/15404634.html