34. Find First and Last Position of Element in Sorted Array

leetcode

Posted by chl on June 29, 2019

题目

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

题意

给定一个升序排序的数组,在给出一个target值,求该值在数组中的起始位置和尾部位置。

例子

Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

题解

二分查找,找到目标值后先前先后找到的起始位置和尾部位置。

代码

func searchRange(nums []int, target int) []int {
    start,end := 0,len(nums)-1
    var mid int
    b,g := -1,-1
    for start<=end{
        mid = (end-start)/2+start
        if nums[mid]==target{
            var i int
            for i=mid-1;(i>=0&&nums[i]==target);i--{
            }
            b = i+1
            for i=mid+1;(i<=len(nums)-1&&nums[i]==target);i++{
                
            }
            g = i-1
            break
        }
        
        if nums[mid]>target{
            end = mid-1
        }else{
            start = mid+1
        }
    }
    return []int{b,g}
}

总结

简单的题目,看到提交率挺低的,以为时多难,原来那么简单。然后我算是明白了,一般提交率比较高的只有两种情况,一种是真的简单,另外一种时真的难,所以很难说。。