牛客网剑指offer刷题Java版-35数字在排序数组中出现的次数

题目描述
统计一个数字在排序数组中出现的次数。
*

法一:找到第一个k,然后向左右两边找。

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
       if(array.length==0)
           return 0;
        int index=FindIndex(array,k,0,array.length-1);
        if(index==-1)
            return 0;
        else{
            int count=1,i=index-1,j=index+1;
            while(i>=0&&k==array[i]){
                i--;
                count++;
            }
            while(j<array.length&&k==array[j]){
                j++;
                count++;
            }
            return count;
        }
    }
    private int FindIndex(int []arr,int k,int left,int right){
        if(left>right)
            return -1;
        int mid=(right-left)/2+left;
        if(k==arr[mid])
            return mid;
        else if(k>mid)
            return FindIndex(arr,k,mid+1,right);
        else
            return FindIndex(arr,k,left,mid-1);
    }
}

法二:找到第一个k和最后一个k,相减

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
       if(array.length==0)
           return 0;
        int first=findFirstK(array,k);
        int last=findLastK(array,k);
        if(first == -1 || last == -1){
            return 0;
        }
        return last-first+1;
    }
    private int findFirstK(int[]arr, int k){
        int l = 0, r = arr.length - 1;
        int mid = (l + r) >> 1;
        while(l <= r){
            if(arr[mid] > k){
                r = mid - 1;
            } else if(arr[mid] < k){
                l = mid + 1;
            } else if(mid - 1 >= 0 && arr[mid - 1] == k){
                r = mid - 1;
            } else{
                return mid;
            }
            mid = (l + r) >> 1;
        }
        return -1;
    }
    private int findLastK(int []arr, int k){
        int l = 0, r = arr.length - 1;
        int mid = (l + r) >> 1;
        while(l <= r){
            if(arr[mid] > k){
                r = mid - 1;
            } else if(arr[mid] < k){
                l = mid + 1;
            } else if(mid + 1 < arr.length && arr[mid + 1] == k){
                l = mid + 1;
            } else{
                return mid;
            }
            mid = (l + r) >> 1;
        }
        return -1;
    }
}

你可能感兴趣的:(Java刷题)