xqCui

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

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

解法一:

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
        int count=0;
        for(int i=0;i<array.length;i++){
           if(array[i]==k)
               count++;
       }
        return count;
    }
}

解法二:

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
      int num = 0;
        if (array != null && array.length > 0) {//分两种搜索,往前,和往后
            int firstKIndex = getFirstK(array, k, 0, array.length - 1);
            int lastKIndex = getLastK(array, k, 0, array.length - 1);
            if (firstKIndex > -1 && lastKIndex > -1)
                num = lastKIndex - firstKIndex + 1;
        }
        return num;
    }
    public  int getFirstK(int[] array, int k, int start, int end) {
        if (start > end)
            return -1;
        int middleIndex = start + (end - start) / 2;
        int middleData = array[middleIndex];
        if (middleData == k) {
            if (middleIndex > 0 && array[middleIndex - 1] != k || middleIndex == 0) {
                return middleIndex;
            } else
                end = middleIndex - 1;
        } else if (middleData > k) {
            end = middleIndex - 1;
        } else
            start = middleIndex + 1;
        return getFirstK(array, k, start, end);
    }
    public  int getLastK(int array[], int k, int start, int end) {
        if (start > end) {
            return -1;
        }
        int middleIndex = (start + end) / 2;
        int middleData = array[middleIndex];
        if (middleData == k) {
            if (middleIndex < array.length - 1 && array[middleIndex + 1] != k || middleIndex == array.length - 1)
                return middleIndex;
            else
                start = middleIndex + 1;
        } else if (middleData < k) {
            start = middleIndex + 1;
        } else
            end = middleIndex - 1;
        return getLastK(array, k, start, end);
 
    }
}

 

posted on 2016-05-28 18:22  xqCui  阅读(135)  评论(0编辑  收藏  举报

导航