Closest Number in Sorted Array

题目:

Given a target number and an integer array A sorted in ascending order, find the index i in A such that A[i] is closest to the given target.

Return -1 if there is no element in the array.

分析:

主要注意一下最后选择start还是end的事儿就行

解法:

class Solution {
public:
    /**
     * @param A an integer array sorted in ascending order
     * @param target an integer
     * @return an integer
     */
    int closestNumber(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 (target <= A[start]) {
            return start;
        } else if (A[end] <= target) {
            return end;
        } else {

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

        }
    }
};

results matching ""

    No results matching ""