zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    h5移动开发css
    js 小数相加异常
    h5上滑刷新(分页)
    js中的 !!
    图片懒加载(延迟加载)原理及实现
    作用域内优先级及this指针
    函数的属性、方法和构造函数
    判断是否为严格模式
    匿名函数递归调用自身
    闭包
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8667477.html
Copyright © 2011-2022 走看看