题目描述
统计一个数字在排序数组中出现的次数。
思路:这题有两个点可以想到使用二分法,
1)排序的数组;
2)暴力求解的复杂度是O(n),要想优化只有二分法的logn级别。
和使用二分法找到某个数出现的区间一样,只不过要多一个变量判断是否找到这个数,因为如果不存在这个数那么两次二分法找到的位置和元素只有一个出现最后一个位置的答案是一样的,所以要多用一个变量进行判断。
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { if(data.size() == 0){ return 0; } int start = 0,end = data.size() - 1; int mid; bool firstFindIt = true; while(start + 1 < end){ mid = start + (end - start) / 2; if(data[mid] == k){ end = mid; } else if(data[mid] < k){ start = mid; } else{ end = mid; } } int firstPos = 0; if(data[start] == k){ firstPos = start; } else if(data[end] == k){ firstPos = end; } else{ firstFindIt = false; } start = 0; end = data.size() - 1; while(start + 1 < end){ mid = start + (end - start) / 2; if(data[mid] == k){ start = mid; } else if(data[mid] < k){ start = mid; } else{ end = mid; } } int lastPos = 0; bool lastFindIt = true; if(data[end] == k){ lastPos = end; } else if(data[start] == k){ lastPos = start; } else{ lastFindIt = false; } if(firstFindIt == true && lastFindIt == true){ return lastPos - firstPos + 1; } return 0; } };