+ 7

How to find an index of a number of array ?

im finding how many numbers that lower than or equal with a value. example: arr = {1, 3, 5, 7, 9} value = 8 answer : 4 (1,3,5,7) and it shouldnt be a brute force because of time limit. Can anyone help me? Sorry for my bad English...

18th Aug 2018, 7:27 AM
I Am A Coder🌍[Not Active]
I Am A Coder🌍[Not Active] - avatar
8 odpowiedzi
+ 6
Ya'iko i think im using c++
18th Aug 2018, 2:07 PM
I Am A Coder🌍[Not Active]
I Am A Coder🌍[Not Active] - avatar
+ 6
ive tried using vector but it seems to be slow... ive got a tle on that question... https://code.sololearn.com/cCkPpHIt1Jf8/?ref=app
18th Aug 2018, 2:11 PM
I Am A Coder🌍[Not Active]
I Am A Coder🌍[Not Active] - avatar
+ 5
just consider yes, but i dont know the implementation of binary search...
18th Aug 2018, 7:57 AM
I Am A Coder🌍[Not Active]
I Am A Coder🌍[Not Active] - avatar
+ 5
In a sorted container, STL's find() algorithm would be the closest choice IF the search key be present. It searches the container for a key value and return an iterator which then can be checked against the end() or begin() members. Here is an example using vector: vector<int> arr = {1, 3, 5, 7, 8, 9}; int value = 8; vector<int>::iterator i; i = find(arr.begin(), arr.end(), value); if ( i != arr.end() ) cout << "# of elements before << value << " is " << i - arr.begin();
18th Aug 2018, 8:18 AM
Babak
Babak - avatar
+ 4
Is the array sorted? If so, you can do something similar to binary search.
18th Aug 2018, 7:41 AM
Vlad Serbu
Vlad Serbu - avatar
+ 2
https://www.sololearn.com/learn/664/?ref=app You could have a look through this to help with the implementation. If it's not sorted, you'll have to sort it and then do this, in which case just going through the list in order would be quicker
18th Aug 2018, 8:17 AM
Dan Walker
Dan Walker - avatar
0
std::upperbound or std::lowerbound is your choice in case if array is sorted.
19th Aug 2018, 6:02 PM
Sergey Ushakov
Sergey Ushakov - avatar
- 2
print(arr.index(3)) output: 1 for PYTHON atleast.
19th Aug 2018, 6:21 AM
Arun Sharma
Arun Sharma - avatar