美文网首页
Last Position of Target

Last Position of Target

作者: 一枚煎餅 | 来源:发表于2016-09-14 08:16 被阅读0次
    Last Position of Target.png

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

    跟 first position of target 相同的題目 只是這次在 mid index 內容 = target 時 移動的是 left 的 index (left = mid)

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

    <pre><code>
    class Solution {

    public:

    /**
     * @param A an integer array sorted in ascending order
     * @param target an integer
     * @return an integer
     */
    int lastPosition(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) left = mid;
            else right = mid;
        }
        if(A[right] == target) return right;
        if(A[left] == target) return left;
        return -1;
    }
    

    };
    <code><pre>

    相关文章

      网友评论

          本文标题: Last Position of Target

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