First Position of Target

题目:

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

If the target number does not exist in the array, return -1.

接口:

class Solution {
public:
    /**
     * @param nums: The integer array.
     * @param target: Target number to find.
     * @return: The first position of target. Position starts from 0. 
     */
    int binarySearch(vector<int> &array, int target) {
        // write your code here

    }
};

分析:

这题目要求O(logn)的复杂度,又是sorted array,话不多说我们来搞二分法。注意要求first position of target所以当(array[mid] == target)的时候,操作是end = mid。

解法:

class Solution {
public:
    /**
     * @param nums: The integer array.
     * @param target: Target number to find.
     * @return: The first position of target. Position starts from 0. 
     */
    int binarySearch(vector<int> &array, int target) {
        // write your code here
        if (array.size() == 0) {
            return -1;
        }

        int start = 0;
        int end = array.size() - 1;

        while (start + 1 < end) {
            int mid = start + (end - start) / 2;

            if (array[mid] == target) {
                end = mid;
            } else if (array[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }

        }

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

results matching ""

    No results matching ""