34. 在排序数组中查找元素的第一个和最后一个位置
34. 在排序数组中查找元素的第一个和最后一个位置
func SearchInts ¶
func SearchInts(a []int, x int) int
SearchInts searches for x in a sorted slice of ints and returns the index as specified by Search.
The return value is the index to insert x
if x is not present (it could be len(a)),他将会返回切片a的长度
- The slice must be sorted in ascending order(升序).
package main
import (
"fmt"
"sort"
)
func searchRange(nums []int, target int) []int {
leftmost := sort.SearchInts(nums,target)
if leftmost == len(nums) || nums[leftmost] != target{
return []int{-1,-1}
}
rightmost := sort.SearchInts(nums,target+1)-1
return []int{leftmost,rightmost}
}
func main(){
fmt.Print(searchRange([]int{1,2,3,4,5},9))
}