First Position of Target
Easy For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.
If the target number does not exist in the array, return -1.
Thoughts
最基本的bin search问题。用STL中lower_bound的实现方法找出数组中第一个和target相等或比target大的数(当target不在时)所在的index, 即最后start/end(它们俩最后相等)所在位置.
基于此思想把模板拓展成找第一个分界点(后半边第一个元素)所在位置. 当end == nums.len时分界点看成可以是非数组内元素, 否则是在nums里. 当落在分界点前时, 把对应的start/end移到mid并加一.
Code
Analysis
Time Complexity: O(lgn)
Previous540. Single Element in a Sorted ArrayNext34. Find First and Last Position of Element in Sorted Array
Last updated
Was this helpful?