码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-04-15 11:44:22      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

 

 

class Solution {
public:
    int lowindex(vector<int>&data,int k,int low,int high)
        {
        if(low<high)
            {
            int i=low,j=high;
            int mid=(i+j)/2;
            if(data[mid]>k)
                return lowindex(data,k,low,mid-1);
            if(data[mid]<k)
                return lowindex(data,k,mid+1,high);
            if(data[mid]==k&&(mid==0||data[mid-1]!=k))
                return mid;
            else return lowindex(data,k,low,mid-1);
        }
       else return low;
    }
    int highindex(vector<int>&data,int k,int low,int high)
        {
        if(low<high)
            {
             int i=low,j=high;
            int mid=(i+j)/2;
            if(data[mid]>k)
                return lowindex(data,k,low,mid-1);
            if(data[mid]<k)
                return lowindex(data,k,mid+1,high);
            if(data[mid]==k&&(mid==data.size()-1||data[mid+1]!=k))
                return mid;
            else return highindex(data,k,mid+1,high);
        }
        else return low;
    }
    int GetNumberOfK(vector<int> data ,int k) {
          if(data.empty())return 0;       
        int low =lowindex(data,k,0,data.size()-1);
        int high =highindex(data,k,0,data.size()-1);
        if(low==high&&data[low]!=k)
            return 0;
        int dis=high-low+1;
        return dis;
    }
};

 

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

标签:

原文地址:http://www.cnblogs.com/daocaorenblog/p/5394797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!