#include <vector>
#include <string>
template <typename Comparable>
const Comparable & findKthLargest( const std::vector<Comparable> & v, const int k){
int counter;
Comparable j;
for (Comparable i : v){
counter = 0;
j = v[i];
for(Comparable p : v){
if(v[p] > j){
counter++;
}
}
if(counter == k){
return v[i];
}
}
return -1;
}
So this is the project I'm working on right now. I am passed a vector of comparables and an integer k. I need to find the "kth" largest comparable in the array given. This code works by iterating through the vector one comparable at a time and checking how many other comparables in the vector are larger than it. (the largest element in the array would yield 0, second largest would yield 1). So for example:
I am passed the vector: { 5,4,7,6,3,8,4,9 } and the tests run are:
REQUIRE( findKthLargest(kth_ints, 0) == 9);
REQUIRE( findKthLargest(kth_ints, 1) == 8);
REQUIRE( findKthLargest(kth_ints, 3) == 6);
I am passing the first two, and not the third one(I think I'm getting 4 instead of 6). I think I should be using pointers here to pull the actual value from the vector rather than the address, but I'm unfamiliar with the syntax for doing so, or where exactly I would need the *'s and &'s. Thank you so much for the help.
Aucun commentaire:
Enregistrer un commentaire