fork download
  1. // Count Occurrence (Lower & Upper Bound)
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int lowerBound(vector<int>& arr, int x) {
  6. int l = 0, r = arr.size();
  7. while(l < r) {
  8. int mid = l + (r - l) / 2;
  9. if(arr[mid] < x) l = mid + 1;
  10. else r = mid;
  11. }
  12. return l;
  13. }
  14.  
  15. int upperBound(vector<int>& arr, int x) {
  16. int l = 0, r = arr.size();
  17. while(l < r) {
  18. int mid = l + (r - l) / 2;
  19. if(arr[mid] <= x) l = mid + 1;
  20. else r = mid;
  21. }
  22. return l;
  23. }
  24.  
  25. int main() {
  26. int n = 6, x = 2;
  27. vector<int> arr = {1,2,2,2,3,4};
  28. cout << upperBound(arr, x) - lowerBound(arr, x);
  29. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
3