思路:
利用二分查找,分别查找待统计数字的头和尾的下标,最后做差加一即为结果。
C++:
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 int GetFirstK(vector<int>& nums, int startpos, int endpos, int k) 6 { 7 if(startpos > endpos) 8 return -1; 9 10 int mid = (startpos + endpos) / 2; 11 12 if(nums[mid] == k) 13 { 14 if(mid == 0 || (mid > 0 && nums[mid - 1] != k)) 15 return mid; 16 else 17 endpos = mid - 1; 18 } 19 else if(nums[mid] < k) 20 { 21 startpos = mid + 1; 22 } 23 else 24 { 25 endpos = mid - 1; 26 } 27 28 return GetFirstK(nums, startpos, endpos, k); 29 } 30 31 int GetLastK(vector<int>& nums, int startpos, int endpos, int k) 32 { 33 if(startpos > endpos) 34 return -1; 35 36 int mid = (startpos + endpos) / 2; 37 int lastpos = nums.size() - 1; 38 39 if(nums[mid] == k) 40 { 41 if(mid == lastpos || (mid < lastpos && nums[mid + 1] != k)) 42 return mid; 43 else 44 startpos = mid + 1; 45 } 46 else if(nums[mid] < k) 47 { 48 startpos = mid + 1; 49 } 50 else 51 { 52 endpos = mid - 1; 53 } 54 55 return GetLastK(nums, startpos, endpos, k); 56 } 57 58 int main() 59 { 60 int a[10] = {1, 2, 3, 3, 3, 3, 3, 4, 4, 5}; 61 vector<int> v(a, a +10); 62 63 cout<<GetLastK(v, 0, 9, 4) - GetFirstK(v, 0, 9, 4) + 1<<endl; 64 }
时间: 2024-09-29 23:34:53