This is still my first week of learning C++, I solved the lower bound STL challenge in HackerRank Lower Bound STL but I'm having time exceeded issue for long input. I'm open to constructive criticism, ways to improve in terms of syntax, style and performance.
You are given \$N\$ integers in the sorted order. Then 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. Lower bound is a function that can be used with a sorted vector.
Input Format
The first line of the input contains the number of integers \$N\$. The next line contains \$N\$ integers in sorted order. The next line contains \$Q\$, the number of queries. Then \$Q\$ lines follow each containing a single integer \$Y\$.
If the same number is present multiple times, you have to print the first index at which it occurs. The input is such that you always have an answer for each query.Constraints
- \$1 \leq N \leq 10^5\$
- \$1 \leq X_i \leq 10^9\$, where \$X_i\$ is \$i^{th}\$ element in the array
- \$1 \leq Q \leq 10^5\$
- \$1 \leq Y \leq 10^9\$
Output Format
For each query you have to print "Yes"(without the quotes) if the number is present and at which index it is present separated by a space. If the number is not present you have to print "No"(without the quotes) followed by the index of the next smallest number just greater than that number. You have to output each query in a new line.
Sample Input
8 1 1 2 2 6 9 9 15 4 1 4 9 15
Sample Output
Yes 1 No 5 Yes 6 Yes 8
Here is my code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
int query;
int queryLength;
{
std::vector<int>::iterator low;
std::vector<int>::iterator foundValue;
std::cin >> N;
std::vector<int> v(N);
//populate the vector
for(int i =0; i<N; i++){
std::cin >> v[i];
}
std::cin >> queryLength;
for(int j = 0; j < queryLength; j++){
std::cin >> query;
foundValue= find(v.begin(), v.end(), query);
if (foundValue != v.end())
{
std::cout << "Yes "<< (foundValue-v.begin()+ 1) << std::endl;
}
else{
low = std::lower_bound (v.begin(), v.end(),query);
std::cout << "No "<< find(v.begin(), v.end(), *low)-v.begin()+ 1 << std::endl;
}
}
}
return 0;
}
find()
is O(n) whilelower_bound()
is O(ln(n)). You can usestd::distance()
to find the index from two iterators. \$\endgroup\$