ninehills / blog

https://ninehills.tech
758 stars 68 forks source link

LeetCode-34. Search for a Range #50

Closed ninehills closed 7 years ago

ninehills commented 7 years ago

问题

https://leetcode.com/problems/search-for-a-range/description/

Given an array of integers 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].

For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

思路

题目简单,直接遍历即可

解答

package main

import "fmt"

// ----------------------
func searchRange(nums []int, target int) []int {
    var i int = 0
    var r = []int{-1, -1}
    for i = 0; i < len(nums); i++ {
        if target == nums[i] {
            if r[0] == -1 {
                r[0] = i
                r[1] = i
            } else {
                r[1] = i
            }
        }
    }
    return r
}

// ----------------------

func main() {
    fmt.Println(searchRange([]int{5, 7, 7, 8, 8, 10}, 8))
}
ninehills commented 7 years ago

4