lc34题GO sort.Searchints函数

177 阅读1分钟

力扣官方解题:

    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}
}

这里运用了sort.SearchInts()函数,其官方文档的解释为:

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)). The slice must be sorted in ascending order.

大概意思是如果x存在就返回x的索引,不存在则返回可以插入位置的索引(有可能是len(a)),这里nums[leftmost] != target判断就有必要了,不可以去掉,而且leftmost == len(nums)要写在前面,避免nums[len(nums)]错误

我的解题

在我知道有这个函数前,写了一个很繁琐的解题,经过几次提交失败补全(很多边界条件考虑不够周全引起的)

func searchRange(nums []int, target int) []int {
   value := []int{-1, -1}
   left, right := 0, len(nums)-1
   temp := -1
   var begin, end int
   for left <= right {
      mid := (left + right) / 2
      if nums[mid] == target {
         temp = mid
         break
      }
      if nums[left] <= target && target <= nums[mid] {
         right = mid - 1
      } else {
         left = mid + 1
      }
   }
   if temp >= 0 {
      for i := 0; nums[temp-i] == nums[temp]; i++ {
         begin = temp - i
         if begin == 0 { // 避免nums[-1]
            break
         }
      }
      for i := 0; nums[temp+i] == nums[temp]; i++ {
         end = temp + i
         if end == len(nums)-1 { // 避免nums[len(nums)]
            break
         }
      }
      value[0] = begin
      value[1] = end
   }
   return value
}