You are viewing a single comment's thread. Return to all comments →
Hello friends,
climbing the leaderboard can be optimized by applying binary search
If interested to know more about the generic algorithm in details-
click here for the video explanation of generic algorithm with complexity analysis.
or you can click on the image too to follow youtube tutorial.
Here is the working solution:-
source code :
static int[] climbingLeaderboard(int[] scores, int[] alice) { int n = scores.length; int m = alice.length; int res[] = new int[m]; int[] rank = new int[n]; rank[0] = 1; for (int i = 1; i < n; i++) { if (scores[i] == scores[i - 1]) { rank[i] = rank[i - 1]; } else { rank[i] = rank[i - 1] + 1; } } for (int i = 0; i < m; i++) { int aliceScore = alice[i]; if (aliceScore > scores[0]) { res[i] = 1; } else if (aliceScore < scores[n - 1]) { res[i] = rank[n - 1] + 1; } else { int index = binarySearch(scores, aliceScore); res[i] = rank[index]; } } return res; } private static int binarySearch(int[] a, int key) { int lo = 0; int hi = a.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == key) { return mid; } else if (a[mid] < key && key < a[mid - 1]) { return mid; } else if (a[mid] > key && key >= a[mid + 1]) { return mid + 1; } else if (a[mid] < key) { hi = mid - 1; } else if (a[mid] > key) { lo = mid + 1; } } return -1; }
Would really appreciate your feedback like, dislike , comment etc. on my video.
Seems like cookies are disabled on this browser, please enable them to open this website
Climbing the Leaderboard
You are viewing a single comment's thread. Return to all comments →
Hello friends,
climbing the leaderboard can be optimized by applying binary search
If interested to know more about the generic algorithm in details-
click here for the video explanation of generic algorithm with complexity analysis.
or you can click on the image too to follow youtube tutorial.
Here is the working solution:-
source code :
Would really appreciate your feedback like, dislike , comment etc. on my video.
Do not forget to upvote, if you find it useful.