Total Occurrence of Target

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



Analysis:
Use binary search to find lowerbound, and count from lowerbound up.
Solution:

public class Solution {
    /*
     * @param A: A an integer array sorted in ascending order
     * @param target: An integer
     * @return: An integer
     */
    public int totalOccurrence(int[] A, int target) {
        if (A == null || A.length == 0) return 0;
        // write your code here
        int start= 0, end= A.length - 1, lower = -1, res = 0;  
        while (start+ 1< end) {  
            int mid = start+ (end- start)/2;  
            if (A[mid] >= target){  
                end= mid;  
            }  else {
                start= mid;
            }
         }
        if (A[start] == target) lower = start;
        else  if (A[end] == target) lower = end;
        else return res;

        for (int i = lower; i < A.length; i++) {
            if (A[i] == target) res++;
            else break;
        }

        return res;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List