Prove safety Offer37: frequency (Java) number that appears in the sort array

Reference chaibubble's blog: https://blog.csdn.net/chaipp0607/article/details/76977687

Analysis of ideas:

Sort the array: array row has a good sequence. (Beginning do not know what that means ..)

  1. Traverse the entire array can be calculated how many values ​​of k, which most likely to occur, the time complexity of O (n).
  2. Using a binary search method to find the values k leftmost and rightmost coordinates L coordinate value k R, k is the number of values of R-L + 1.
    The title does not say the array is descending or ascending order, they can add analysis to determine the actual cow off-line programming default is ascending, descending order without regard no problem.

Visit: binary search

Subject description:

Count the number of times a number that appears in the sort array.

Java code:

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
       //排序数组:排好序的数组
       int sum=0;
       int l=leftk(array,k,0,array.length-1);
       int r=rightk(array,k,0,array.length-1);
       if(l>-1&&r>-1){
        sum= r-l+1;
       }
        return sum;
    }
    public static int leftk(int []arr,int k,int left,int right){
        if(left>right){
            return -1;
        }
        int middle=(right+left)/2;
        if(arr[middle]==k){
            if(middle!=left&&arr[middle-1]!=k||middle==left){
                return middle;
            }
            else right=middle-1;
        }
        else if(arr[0]<=arr[arr.length-1]){
            if(arr[middle]>k){
                right=middle-1;
            }
            else if(arr[middle]<k){
                left=middle+1;
            }
        }
        else if(arr[0]>arr[arr.length-1]){//假设当时排序数组是由大到小的,不写也可以的
            if(arr[middle]>k){
                left=middle-1;
            }
            else if(arr[middle]<k){
                right=middle+1;
            }
        }
        return leftk(arr,k,left,right);
    }
    
    public static int rightk(int []arr,int k,int left,int right){
        if(left>right){
            return -1;
        }
        int middle=(right+left)/2;
        if (arr[middle]==k){
            if(middle!=right&&arr[middle+1]!=k||middle==right){
                return middle;
            }
            else{
                left=middle+1;
            }
        }
        else if(arr[0]<=arr[arr.length-1]){
            if(arr[middle]>k){
                right=middle-1;
            }
            else {
                left=middle+1;
            }
        }
        else if(arr[0]>arr[arr.length-1]){//假设当时排序数组是由大到小的,不写也可以的
            if(arr[middle]>k){
                left=middle+1;
            }
            else{
                right=middle-1;
            }
        }
        return rightk(arr,k,left,right);
    }
}

Guess you like

Origin www.cnblogs.com/dongmm031/p/12222932.html