Post

Leetcode - 704. Binary Search

Leetcode - 704. Binary Search

Hits

  • Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

    You must write an algorithm with O(log n) runtime complexity.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func search(nums []int, target int) int {
    low, high := 0, len(nums)-1
    for low<=high{
        mid := (low+high)/2
        fmt.Println(mid)
        if nums[mid]==target{
            return mid
        }else if target>nums[mid]{
            low = mid+1
        }else{
            high = mid-1
        }
    }
    return -1
}

This post is licensed under CC BY 4.0 by the author.