LintCode: First Position of Target

C++

Binary Search

陷阱:找到index最小的。

 1 class Solution {
 2 public:
 3     /**
 4      * @param nums: The integer array.
 5      * @param target: Target number to find.
 6      * @return: The first position of target. Position starts from 0. 
 7      */
 8     int binarySearch(vector<int> &array, int target) {
 9         // write your code here
10         int ret = array.size();
11         int left = 0, right = array.size()-1;
12         while (left <= right) {
13             int mid = (left + right) >> 1;
14             if (array[mid] == target) {
15                 ret = min(ret, mid);
16                 right = mid - 1;
17             }
18             if (array[mid] > target) {
19                 right = mid - 1;
20             }
21             if (array[mid] < target) {
22                 left = mid + 1;
23             }
24         }
25         if (ret == array.size()) {
26             ret = -1;
27         }
28         return ret;
29     }
30 };

 

posted @ 2015-12-02 12:47  ZH奶酪  阅读(555)  评论(0编辑  收藏  举报