[Golang][Leetcode][Array]刷題系列-34-Binary Search

Contents
34. Find First and Last Position of Element in Sorted
Array
Level : Medium
原題連結 : Click
題目 :
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example :
Note
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
以下是我自己的解法 - O(lgn)
Runtime: 4 ms, faster than 99.23% of Go online submissions for Find First and Last Position of Element in Sorted Array.
解題思路 :
這是一個經典的Binary Search變種題,通常Binary Search會有4大變種題
- 找到第一個值等於target的elements
- 找到最後一個值等於target的elements
- 找到第一個大於等於target的elements
- 找到最後一個值小於等於target的elements
而這題我的實現方法是用 第1種 與 第2種 個實現一個function,再回傳答案
|
|
最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!