统计一个整数在排序(升序)整数数组中出现的次数

统计一个整数在排序(升序)整数数组中出现的次数。

二分查找,分别查找大于目标值0.5(随便一个大于0小于1的数即可)和小于目标值0.5的数,取两位置之差。

Python

# -*- coding:utf-8 -*-
class Solution:
    def GetNumberOfK(self, data, k):
        def binarySearch(data, k):
            low = 0
            high = len(data) -1
            while low <= high:
                mid = (low + high) >> 1
                if data[mid] < k:
                    low = mid + 1
                elif data[mid] > k:
                    high = mid - 1
            return low
        if not data:
            return 0
        return binarySearch(data, k+0.5)-binarySearch(data, k-0.5)

Java

public class Solution {
    public int BinarySearch(int [] array, double k) {
        int low = 0, high = array.length-1, mid = 0;
        while(low <= high) {
            mid = (low + high) / 2;
            if(k >= array[mid]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return low;
    }
    public int GetNumberOfK(int [] array , int k) {
        return BinarySearch(array, k+0.5) - BinarySearch(array, k-0.5);
    }
}
posted @ 2017-09-01 17:51  HitAnyKey  阅读(436)  评论(0编辑  收藏  举报