📜  查找具有最低值的K个项目

📅  最后修改于: 2021-04-23 18:18:42             🧑  作者: Mango

给定项目及其值的列表。任务是找到具有最低价值的k个物品。两个项目可能具有相同的值,在这种情况下,名称(在字典上)为第一的项目将被赋予更高的优先级。

例子:

Input : items[] = {Bat, Gloves, Wickets, Ball}, 
        values[] = {100, 50, 200, 100}
        k = 2
Output : Gloves Ball
Explanation : 
Gloves has the lowest value.
Ball and Bat has the same value but Ball comes first lexicographically.

方法:
可以通过根据值贪婪地选择项目来解决此问题。我们将按值的升序对项列表进行排序,如果值相同,则将按字典顺序对项进行升序排序。
我们将数据以成对的形式存储在向量中,并将使用带有布尔压缩函数的内置排序函数,该函数将用于比较两个项目。

下面是上述方法的实现:

// C++ implementation of above approach
#include 
using namespace std;
  
// Boolean Comparator Function
// to compare two pairs of item-value
bool comp(pair A, pair B)
{
    // Compare the name if the values are equal
    if (A.second == B.second)
        return A.first < B.first;
  
    // Else compare values
    return A.second < B.second;
}
  
// Driver code
int main()
{
    int k = 2;
    int n = 3;
  
    // Store data in a vector of Item-Value Pair
    vector > items;
  
    // inserting items-value pairs in the vector
    items.push_back(make_pair("Bat", 100));
    items.push_back(make_pair("Gloves", 50));
    items.push_back(make_pair("Wickets", 200));
    items.push_back(make_pair("Ball", 100));
  
    // Sort items using Inbuilt function
    sort(items.begin(), items.end(), comp);
  
    // Print top k values
    // or if n is less than k
    // Print all n items
    for (int i = 0; i < min(n, k); ++i) {
        cout << items[i].first << '\n';
    }
  
    return 0;
}

输出 :

Gloves
Ball

时间复杂度– O(NlogN)

进一步的优化:我们可以使用基于堆的方法来有效地找到k个最大元素。