java - 按两个条件排序

标签 java algorithm sorting search

我有一个包含字段的 n 对象数组:ID、价格。相同的 ID 可能在一个数组中出现多次。我想为每个 ID 找到最便宜的 k 且不超过 m 对象。

同时,k <= n, m <= k。

喜欢:

n = 1,000,000
k = 10,000
m = 50
class Issue {
    int ID;
    int price;

    public Issue(int ID, int price) {
        this.ID = ID;
        this.price = price;
    }
}
Issue[] arr = {
    new Issue(1, 100),
    new Issue(1, 150),
    new Issue(1, 200),

    new Issue(2, 1),
    new Issue(2, 2),
    new Issue(2, 3),

    new Issue(3, 4),
    new Issue(3, 5),
    new Issue(3, 30),
    new Issue(3, 6),

    new Issue(4, 7),
    new Issue(4, 8),
    new Issue(4, 9),
    new Issue(4, 10),
};

如果:

n = 14
k = 5
m = 2

决定如:

new Issue(2, 1),
new Issue(2, 2),
new Issue(3, 4),
new Issue(3, 5),
new Issue(4, 7),

我使用 java 流解决了这个问题,但是使用了几种类型,O 的结果很糟糕。您建议使用什么算法来解决?

@Xiangpeng 感谢您的回答。你是认真的吗?

        int k = 5; // only k cheapest from array n
        int m = 2; //max same iDs
        Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
        stream(arr).forEach(product -> {
            if (!map.containsKey(product.ID)) {
                PriorityQueue<Integer> integers = new PriorityQueue<>(reverseOrder());
                integers.add(product.price);
                map.put(product.ID, integers);
            } else {
                PriorityQueue<Integer> integers = map.get(product.ID);
                integers.add(product.price);
                map.put(product.ID, integers);
                if (integers.size() > m) {
                    integers.poll();
                }
            }
        });
        PriorityQueue<Integer> priorityQueueK = new PriorityQueue<>(k, reverseOrder());
        for (PriorityQueue<Integer> values : map.values()) {
            for (int i = 0; i < values.size(); ) {
                priorityQueueK.add(values.poll());
                if (priorityQueueK.size() > k) {
                    priorityQueueK.poll();
                }
            }
        }

最佳答案

您需要一个具有两个条件的比较器。

Comparator.comparing((Issue a) -> a.ID ) 通过 ID 创建一个新的比较器

thenComparing 添加第二个条件,在本例中比较价格

list.sort(Comparator.comparing((Issue a)-> a.ID ).thenComparing((a,b)-> Integer.compare(a.price, b.price) ));

我建议使用 getters 和 setters 方法

list.sort(Comparator.comparing((Issue a)-> a.getId() ).thenComparing((a,b)-> Integer.compare(a.getPrice(), b.getPrice()) ));

关于java - 按两个条件排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54371079/

相关文章:

java - 如何使用 ADB/AM 调试 Android 应用程序?

java - Servlet 中可关闭的非线程安全资源

java - 在 Java 中处理巨大的文本文件

java - 硬币变化递归所有解决方案到不同的解决方案

algorithm - 如何检查2个数字是否具有相同的位数和长度?

SQL WHERE IN (...) 按列表顺序排序?

c# - 为什么 DataTable.Select 默认对数据进行排序

java - 我的主类应该在项目中的什么位置创建?

java - 没有主键的表的 JPA 实体

c++ - 从 vector 末尾开始的插入排序