No.195 - LeetCode34. Find First and Last Position of Element in Sorted Array - 经典左右届二分


func searchRange(nums []int, target int) []int {
	n := len(nums)
	if n == 0 {
		return []int{-1,-1}
	}
	return []int{LBound(-1,n-1,nums,target),RBound(0,n,nums,target)}
}

func LBound(L,R int , nums []int, target int) int {
	if L+1 >= R {
		if nums[R] == target {
			 return R
		}
		return -1
	}
	mid := (L+R)/2
	if target <= nums[mid] {
		return LBound(L,mid,nums,target)
	}
	return LBound(mid,R,nums,target)
}

func RBound(L,R int, nums []int, target int) int {
	if L+1 >= R {
		if nums[L] == target {
			return L
		}
		return -1
	}
	mid := (L+R)/2
	if target < nums[mid] {
		return RBound(L,mid,nums,target)
	}
	return RBound(mid,R,nums,target)
}

你可能感兴趣的:(leetcode)