LF.24.Total Occurance

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

Examples

A = {1, 2, 3, 4, 5}, T = 3, return 1
A = {1, 2, 2, 2, 3}, T = 2, return 3
A = {1, 2, 2, 2, 3}, T = 4, return 0
Corner Cases

What if A is null? We should return 0 in this case.

 

 1 public class Solution {
 2   public int totalOccurrence(int[] array, int target) {
 3     // Write your solution here
 4     if (array == null || array.length == 0 ) {
 5         return 0 ;
 6     }
 7     //find the first occurance and the last occurance then +1 is the # of items in between
 8     int leftIndex = firstOccurence(array, target);
 9     int rightIndex = lastOccurence(array, target);
10     //if either side not found, means there is no match
11     if (leftIndex == -1 || rightIndex == -1) {
12         return 0 ;
13     }
14     // 1 2 3 : 1st = 1 last= 3 totally should be 3 -1 +1  = 3 occurance
15     if(leftIndex <= rightIndex){
16         return (rightIndex - leftIndex) +1  ;
17     }
18     return 0;
19   }
20 
21   private int firstOccurence(int[] array, int target){
22     int left = 0, right = array.length - 1 ;
23     while(left + 1 < right){
24         int mid = left + (right - left)/2 ;
25         if (array[mid] == target) {
26             right = mid ;
27         } else if(array[mid] < target){
28             left = mid ;
29         } else {
30             right = mid ;
31         }
32     }
33     if (array[left] == target) {
34         return left;
35     }
36     if (array[right] == target) {
37         return right ;
38     }
39     return -1 ;
40   }
41 
42   // -1 means there is no target
43   private int lastOccurence(int[] array, int target){
44     int left = 0, right = array.length - 1 ;
45     while(left + 1 < right){
46         int mid = left + (right - left)/2 ;
47         if (array[mid] == target) {
48             left = mid ;
49         } else if(array[mid] < target){
50             left = mid ;
51         } else {
52             right = mid ;
53         }
54     }
55     if (array[right] == target) {
56         return right ;
57     }
58     if (array[left] == target) {
59         return left;
60     }
61     return -1 ;
62   }
63 }

 

posted @ 2018-03-29 01:29  davidnyc  阅读(265)  评论(0编辑  收藏  举报