本文準備講解1個簡單的算法編程問題, 這個算法編程問題來自LintCode平臺。不了解.LintCode平臺的讀者可以閱讀筆者文章(在線編程平臺推薦-LeetCode)。問題的英文版本描述如下:
First Position of Target
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.
Example
If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
? 問題的中文版本描述:
二分查找
給定一個排序的整數(shù)數(shù)組(升序)和一個要查找的整數(shù) target,用O(logn)的時間查找到 target 第一次出現(xiàn)的下標(從0開始),如果 target 不存在于數(shù)組中,返回-1。
樣例
在數(shù)組[1, 2, 3, 3, 4, 5, 10]中二分查找3,返回2。
? 剛好JAVA語言支持對數(shù)組的二分查找,所以這個問題很有價值。JAVA語言自帶的數(shù)組二分查找函數(shù)無法支持數(shù)組中有重復(fù)數(shù)據(jù)的狀況,當(dāng)數(shù)組中有重復(fù)數(shù)據(jù)時,自帶函數(shù)不保證返回的返回值為需要的目標數(shù)據(jù)數(shù)組下標號。比如對樣例數(shù)組,查找3返回3;而不是題目需要的2。為了處理重復(fù)數(shù)據(jù)的問題,必須對經(jīng)典二分查找算法做改造。關(guān)鍵的算法為:找到目標數(shù)據(jù)后,不能中斷查找算法;繼續(xù)尋找數(shù)組下標號最小的目標數(shù)據(jù)項。
? 算法的代碼列表如下:
? 現(xiàn)在公布1種高效的算法方案,該方案對應(yīng) LintCode 平臺表現(xiàn)更強。