Sword refers to Offer-34-the number of times the number appears in the sorted number

Title description

Count the number of times a number appears in the sorted array.

Idea analysis

This question is quite simple, I have already told you here, the sorted array. Sort the array first. Get an ordered array, and those repeated data must be arranged together. Therefore, you only need to traverse to that data, and then compare it with the next data to see if it is equal. If it is not equal, it means the search has been completed. What needs to be noted here is that you need a quantity to judge whether it is out of bounds, because you need to compare the previous one with the next one, and you need a record to go to.

import java.util.Arrays;
public class Solution {
    
    
    public int GetNumberOfK(int [] array , int k) {
    
    
       if(array==null||array.length==0) return 0;
        Arrays.sort(array);//这里直接使用JDK1.8自带的排序方法,注意不是传统意义的快排了而是一种叫做dual-pivot quicksort 的排序方式,
        int count = 0;
        int j = 1;
        for(int i = 0 ;i<array.length;i++){
    
    
            j++;//作为一个array的边界探测指针
            if(array[i]==k){
    
    
                count++;
                if(j>array.length||array[i]!=array[i+1]){
    
    
                    //当j到达了末尾或者是末尾的值不等于前一个值
                    break;
                }
            }
        }
        return count;
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107419373