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
.
java
public class Solution {
/**
* @param A an integer array sorted in ascending order
* @param target an integer
* @return an integer
*/
public int totalOccurrence(int[] A, int target) {
// Write your code here
if (A == null || A.length == 0) {
return 0;
}
if (A[0] > target || A[A.length - 1] < target) {
return 0;
}
int start = 0;
int end = A.length - 1;
int mid = 0;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A[mid] > target) {
end = mid;
} else if (A[mid] < target) {
start = mid;
} else {
start = mid;
}
}
int count = 0;
if (A[end] == target) {
while (end >= 0 && A[end] == target) {
count++;
end--;
}
return count;
}
if (A[start] == target) {
while (start >= 0 && A[start] == target) {
count++;
start--;
}
return count;
}
return 0;
}
}
python
class Solution:
"""
@param: A: A an integer array sorted in ascending order
@param: target: An integer
@return: An integer
"""
def totalOccurrence(self, A, target):
# write your code here
if A is None or len(A) == 0:
return 0
if target < A[0] or target > A[-1]:
return 0
start, end = 0, len(A) - 1
while start + 1 < end:
mid = (end - start) / 2 + start
if A[mid] >= target:
end = mid
else:
start = mid
count = 0
if A[start] == target:
while start < len(A) and A[start] == target:
count += 1
start += 1
return count
if A[end] == target:
while end < len(A) and A[end] == target:
count += 1
end += 1
return count
return 0