备忘

数字在排序数组中出现的次数

http://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
        if(k < array[0] || k > array[array.length-1]){
            return 0;
        }
        int left = 0;
        int right = array.length -1;
        int count = 0;
        while(left < right){
            int mid = (left+right)/2;
            if(array[mid] > k){
                right = mid;
            }else if(array[mid] < k){
                left = mid;
            }else{
                count++;
                int prev = mid-1;
                int foll = mid+1;
                while(prev >= 0){
                    if(array[prev] == k){
                        prev--;
                        count++;
                    }else{
                        break;
                    }
                }
                while(foll <= array.length-1){
                    if(array[foll] == k){
                        foll++;
                        count++;
                    }else{
                        break;
                    }
                }
            }
        }
        return count;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务