队列
队列是一种受限的线性表,对于大部分线性表而言,通常除了第一个和最后一个数据元素之外,其他数据元素都是首尾相接的。
- 先来的元素在队首,后来的只能在末尾,不允许插队。
- 只能在表的前端进行删除,后端进行插入。FIFO
优先级队列
- 优先级队列不再遵循FIFO的规则,而是按照自定义规则(优先级高低)将对应元素取出队列,比如取出优先级高的元素,或者淘汰优先级低的元素。
- 实现方式两种:入队的时候找准位置,或者出队的时候找准位置
- Java中的PriorityBlockingQueue是基于PriorityQueue的再次包装,都是基于堆数据结构实现。
- 数组实现方式
代码
public class KSmallestPairs {
public static List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> que = new PriorityQueue<>((a, b) -> a[0] + a[1] - b[0] - b[1]);
List<List<Integer>> res = new ArrayList<>();
//边界限制
if (nums1.length == 0 || nums2.length == 0 || k == 0) {
return res;
}
for (int i = 0; i < nums1.length && i < k; i++) {
que.offer(new int[]{nums1[i], nums2[0], 0});
}
//
while (k-- > 0 && !que.isEmpty()) {
int[] cur = que.poll();
res.add(Arrays.asList(cur[0], cur[1]));
if (cur[2] == nums2.length - 1) continue;//????
que.offer(new int[]{cur[0], nums2[cur[2] + 1], cur[2] + 1});
}
return res;
}
public static void main(String[] args) {
List<List<Integer>> result = kSmallestPairs(new int[]{1, 7}, new int[]{2, 4, 6}, 3);
result.forEach(System.out::print);
//test PriorityQueue
PriorityQueue<int[]> que = new PriorityQueue<>((a, b) -> a[0] + a[1] - b[0] - b[1]);
que.offer(new int[]{5, 5, 1});
que.offer(new int[]{6, 6, 9});
que.poll();//优先级越高,越先弹出。优先级从0-n 逐级上升
System.out.println(Arrays.deepToString(que.toArray()));
}
}