Classical Bianry Search

题目:

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

分析:

基本题。

解法:

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

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

        if (A[start] == target) {
            return start;
        }

        if (A[end] == target) {
            return end;
        }

        return -1;
    }
};

results matching ""

    No results matching ""