Lintcode14 First Position of Target Solution 題解

【題目描述】

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.

給定一個排序的整數數組(升序)和一個要查找的整數target,用O(logn)的時間查找到target第一次出現的下標(從0開始),如果target不存在於數組中,返回-1。

【題目鏈接】

http://www.lintcode.com/en/problem/first-position-of-target/

【題目解析】

這題目要求O(logn)的複雜度,又是sorted array,話不多說我們來搞二分法。注意要求first position of target所以當(array[mid] == target)的時候,操作是end = mid。

二分查找到第一個target後使用逐個向前查詢第一個target

全程使用二分查找

【答案鏈接】

http://www.jiuzhang.com/solutions/first-position-of-target/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章