HackerRank C++ Lower Bound-STL



You are given N integers in sorted order. Also, you are given Q queries. In each query, you will be given an integer and you have to tell whether that integer is present in the array. If so, you have to tell at which index it is present and if it is not present, you have to tell the index at which the smallest integer that is just greater than the given number is present.



  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7. int main()
  8. {
  9. int m, num;
  10. cin >> m;
  11. vector<int> v;
  12. for (int i=0; i<m; i++)
  13. {
  14. cin >> num;
  15. v.push_back(num);
  16. }
  17. int n, val;
  18. cin >> n;
  19. for (int i=0; i<n; i++)
  20. {
  21. cin >> val;
  22. vector<int>::iterator low = lower_bound(v.begin(), v.end(), val);
  23. if (v[low - v.begin()] == val)
  24. cout << "Yes " << (low - v.begin()+1) << endl;
  25. else
  26. cout << "No " << (low - v.begin()+1) << endl;
  27. }
  28. return 0;
  29. }

download android app