# Total Occurrence of Target

{% embed url="<https://www.lintcode.com/problem/462/>" %}

## Solution 1 (Java)

```java
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;
        }

        int start, end;
        int left = 0, right = A.length - 1;

        // find left end point of the range
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (A[mid] < target) {
                left = mid;
            } else {
                right = mid;
            }
        }
        if (A[left] == target) {
            start = left;
        } else if (A[right] == target) {
            start = right;
        } else {
            return 0;
        }

        // find right end point of the range
        left = 0; right = A.length -1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (A[mid] > target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (A[right] == target) {
            end = right;
        } else if (A[left] == target) {
            end = left;
        } else {
            return 0;
        }

        return end - start + 1;
    }
}
```

### Notes

* We use the similar approach in the [first position of target](/algo/binary-search/first-position-of-target.md) and the [last position of target](/algo/binary-search/last-position-of-target.md) to find the left and right end points of the range for the `target`.
* Eventually, we return the length of that range.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.yushunchen.com/algo/binary-search/total-occurrence-of-target.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
