中级农民
- 积分
- 101
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-2-13
- 最后登录
- 1970-1-1
|
- import java.util.*;
- class QueueNode {
- int value, array, index;
- public QueueNode(int array, int index, int value) {
- this.array = array;
- this.index = index;
- this.value = value;
- }
- }
- public class SortedKArrays {
- private PriorityQueue<QueueNode> pq;
- private int[][] arrays;
-
- public SortedKArrays(int[][] arrays) {
- this.arrays = arrays;
- int k = arrays.length;
-
- pq = new PriorityQueue<>(k, new Comparator<QueueNode>() {
- @Override
- public int compare(QueueNode a, QueueNode b) {
- return a.value - b.value;
- }
- });
-
- for (int i = 0; i < k; i++) {
- if (arrays[i].length > 1) {
- pq.offer(new QueueNode(i, 0, arrays[i][0]));
- }
- }
- }
- public boolean hasNext() {
- return !pq.isEmpty();
- }
- public int next() {
- QueueNode cur = pq.poll();
- int newIndex = cur.index + 1;
- if (newIndex < arrays[cur.array].length) {
- pq.offer(new QueueNode(cur.array, newIndex, arrays[cur.array][newIndex]));
- }
- return cur.value;
-
- }
- public static void main(String[] args) {
- int[][] arrays = {{1, 4, 5}, {2, 7, 10}, {2, 4}, {2, 3}, {2, 8}};
- SortedKArrays sa = new SortedKArrays(arrays);
- while (sa.hasNext()) {
- System.out.println(sa.next());
- }
- }
- }
复制代码 |
|