Total Occurence of Target

题目:

Given a target number and an integer array sorted in ascending order. Find the total number of occurrences of target in the array.

Example

Given [1, 3, 3, 4, 5] and target = 3, return 2.

Given [2, 2, 3, 4, 6] and target = 4, return 1.

Given [1, 2, 3, 4, 5] and target = 6, return 0.

分析:

这题目用到二分法是没有问题的,但是需要注意,宁愿做两次二分法,也强过做while搜索,因为做while搜索最坏情况下复杂度可以达到O(n)。

解法:

class Solution {
public:
    /**
     * @param A an integer array sorted in ascending order
     * @param target an integer
     * @return an integer
     */
    int totalOccurrence(vector<int>& A, int target) {
        // Write your code here
        if (A.size() == 0) {
            return 0;
        }
        int start = 0;
        int end = A.size() - 1;

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

        int indexStart = 0;
        if (A[start] == target) {
            indexStart = start;
        } else if (A[end] == target) {
            indexStart = end;
        } else {
            return 0;
        }

        start = 0;
        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;
            }
        }

        int indexEnd = 0;
        if (A[end] == target) {
            indexEnd = end;
        } else {
            indexEnd = start;
        } 

        return indexEnd - indexStart + 1;
    }
};

results matching ""

    No results matching ""