【題目描述】
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.
給定一個(gè)排序的整數(shù)數(shù)組(升序)和一個(gè)要查找的整數(shù)target锯蛀,用O(logn)的時(shí)間查找到target第一次出現(xiàn)的下標(biāo)(從0開始),如果target不存在于數(shù)組中次慢,返回-1旁涤。
【題目鏈接】
http://www.lintcode.com/en/problem/first-position-of-target/
【題目解析】
這題目要求O(logn)的復(fù)雜度,又是sorted array迫像,話不多說我們來搞二分法劈愚。注意要求first position of target所以當(dāng)(array[mid] == target)的時(shí)候,操作是end = mid侵蒙。
二分查找到第一個(gè)target后使用逐個(gè)向前查詢第一個(gè)target
全程使用二分查找
【答案鏈接】