面试题38:数字在排序数组中出现的次数

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

解法:二分查找,算法复杂度为O(logN).

 1   int getFirstIndexOfK(vector<int>&data, int k)
 2   {
 3     int n = data.size();
 4     if (n == 0)
 5      return -1;
 6         int left = 0;
 7     int right = n-1;
 8         while (left <= right)
 9     {
10          int middle = (left+right)/2;
11      if (data[middle] < k)
12        left = middle+1;
13      else if (data[middle] > k)
14        right = middle - 1;
15      else
16      {
17        if (middle == 0 || (middle != 0 && data[middle-1] < k))
18          return middle;
19        else
20          right = middle-1;
21      }
22    }
23       return -1; 
24  }
 1  1 int getLastIndexOfK(vector<int>&data, int k)
 2   {
 3     int n = data.size();
 4     if (n == 0)
 5      return -1;
 6         int left = 0;
 7     int right = n-1;
 8         while (left <= right)
 9     {
10          int middle = (left+right)/2;
11      if (data[middle] < k)
12        left = middle+1;
13      else if (data[middle] > k)
14        right = middle - 1;
15      else
16      {
17        if (middle == n-1 || (  data[middle+1] > k))
18          return middle;
19        else
20          left = middle+1;
21      }
22    }
23       return -1; 
24  }
int getNumberOfK(vector<int>&data, int k)
{
     int number = 0;
    if (data.size()!=0)
   {
       int first = getFirstIndexOfK(data,k);
      int last = getLastIndexOfk(data,k);
      if (first > -1 && last > -1)
         number = last-first+1;  
    }  
    return number;
}

 

posted @ 2015-07-06 16:46  Rosanne  阅读(168)  评论(0编辑  收藏  举报