Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. Its leaderboard works like this:
-The player with the highest score is ranked number on the leaderboard.
-Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.
For example, the four players on the leaderboard have high scores of 100, 90, 90 and 80. Those players will have ranks 1, 2, 2 and 3 respectively. If Alice's scores are 70, 80 and 105 her rankings after each game are 4th, 3rd and 1st.
#include <bits/stdc++.h>
using namespace std;
struct table{
int rank;
int score;
};
This is a modified binary search function iplementation for searching the score.
int search(vector<table> v,int low,int high,int n,int x){
if(low<=high){
int mid =(high+low)/2;
if((v[mid].score==x) || (mid==0 && v[mid].score<x))
return v[mid].rank;
if(mid==n-1 && v[mid].score>x)
return (v[mid].rank + 1);
if(v[mid].score>x && x>v[mid+1].score && mid<n-1)
return v[mid+1].rank;
if(v[mid].score>x)
return search(v,mid+1,high,n,x);
else
return search(v,low,mid-1,n,x);
}
return -1;
}
Main climbingLeaderboard function
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
vector<table> v;
vector<int> res;
int n = scores.size();
int m = alice.size();
int x=1;
for(int i=0 ; i<n ; i++){
if(scores[i]!=scores[i-1] && i>0)
x++;
v[i].rank = x;
v[i].score = scores[i];
}
int z;
for(int i=0 ; i<m ; i++){
x=alice[i];
z = search(v,0,n-1,n,x);
res.push_back(z);
}
return res;
}
Driver Program
int main(){
int scores_count;
cin >> scores_count;
vector<int> scores; `//vector for storing leaderboard scores`
int k;
for(int i=0 ; i<scores_count ; i++){
cin >> k;
scores.push_back(k);
}
int game_count; `//number of games played by alice`
vector<int> Alice; `//vector for storing Alice's scores`
for(int i=0 ; i<game_count ; i++){
cin >> k;
alice.push_back(k);
}
vector<int> result; `//vector for storing result rank of each game of Alice`
result = climbingLeaderboard(scores,alice);
for(auto i = result.begin() ; i!=result.end() ; i++){
cout << *i << endl;
}
return 0;
}
Problem: In your climbingLeaderboard function, the first loop will attempt to access scores[i-1]
when i is set to 0, resulting in a negative index for a std::vector
access.
Fix: Change the for loop to start from i=1.
Problem 2: You access v
by index without instantiating any structures to hold the data (e.g. v[i].rank = x
).
Fix 2: Create an instance of the structure and write the data to it, then push it back into the vector v
. Alternatively, reserve the memory for the whole vector as a preallocation.
Problem 3: On closer inspection, your search functionality is definitely broken. You should probably test this in isolation from the rest of the code.