美文网首页
Classical Binary Search

Classical Binary Search

作者: 一枚煎餅 | 来源:发表于2016-09-14 13:34 被阅读0次
    Classical Binary Search.png

    ===================== 解題思路 =====================

    基本的二分法搜尋 找到 A[mid] = target 則回傳 否則 return -1

    ===================== C++ code ====================

    <pre><code>
    class Solution {

    public:

    /**
     * @param A an integer array sorted in ascending order
     * @param target an integer
     * @return an integer
     */
    int findPosition(vector<int>& A, int target) {
        // Write your code here
        if(A.size() == 0) return -1;
        int left = 0, right = A.size() -1;
        while(left + 1 < right)
        {
            int mid = left + (right - left) / 2;
            if(A[mid] == target) return mid;
            if(A[mid] > target) right = mid;
            else left = mid;
        }
        return -1;
    }
    

    };
    <code><pre>

    相关文章

      网友评论

          本文标题:Classical Binary Search

          本文链接:https://www.haomeiwen.com/subject/tnyvettx.html