Write a method called kthLargest that accepts an integer k and an array a as its
ID: 3554943 • Letter: W
Question
Write a method called kthLargest that accepts an integer k and an array a as its parameters and returns the element such that k elements have greater or equal value. If k = 0, return the largest element; if k = 1, return the second largest element, and so on.
For example, if the array passed contains the values {74, 85, 102, 99, 101, 56, 84} and the integer k passed is 2, your method should return 99 because there are two values at least as large as 99 (101 and 102).
Assume that 0 <= k < a.length. (Hint: Consider sorting the array, or a copy of the array first.)
Please show your whole program and only show answer in javascript please. Thanks!
Explanation / Answer
#include
#include
#include
using namespace std;
vector smallest(vector L, int k) {
int sup;
vector sublist;
if (L.size() <= k) {
return L;
}
for (int i = 0; i < L.size(); ++i) {
if (i sup) {
sublist.push_back(sup);
sup = L[i];
} else {
sublist.push_back(L[i]);
}
} else {
if (L[i] < sup) {
sublist.push_back(L[i]);
}
}
}
if (sublist.size() < k) {
sublist.push_back(sup);
return sublist;
} else {
return smallest(sublist, k);
}
}
int main(int argc, char **argv) {
vector L, sublist;
while (
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.