+ 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...
8 odpowiedzi
+ 6
Ya'iko i think im using c++
+ 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
+ 5
just consider yes, but i dont know the implementation of binary search...
+ 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();
+ 4
Is the array sorted? If so, you can do something similar to binary search.
+ 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
0
std::upperbound or std::lowerbound is your choice in case if array is sorted.
- 2
print(arr.index(3))
output:
1
for PYTHON atleast.