Last Position of Target

题目:

Find the last position of a target number in a sorted array. Return -1 if target does not exist.

Example, given [1, 2, 2, 4, 5, 5]. For target = 2, return 2.

分析:

基本题,没什么特殊之处。

解法:

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 start = 0;
        int end = A.size() - 1;

        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] == target) {
                start = mid;
            } else if (A[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }

        if (A[end] == target) {
            return end;
        } else if (A[start] == target) {
            return start;
        } 
        return -1;
    }
};

results matching ""

    No results matching ""