leetcode 373. Find K Pairs with Smallest Sums | 373. 查找和最小的K对数字(小根堆)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 373. Find K Pairs with Smallest Sums | 373. 查找和最小的K对数字(小根堆)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/find-k-pairs-with-smallest-sums/
題解
本來以為是個雙指針+貪心,但是后來發現如果用雙指針的話,指針并不是只能++,還需要往回走,否則會丟失一些組合
看了 Related Topics 之后才發現,這是個考察 Heap 的題。
相關問題:leetcode 347. Top K Frequent Elements | 347. 前 K 個高頻元素(大根堆)
于是復制之前的模板,建了個小根堆,搞定。
class Solution {public static class HeapNode {int sum;int n1;int n2;public HeapNode(int n1, int n2) {this.n1 = n1;this.n2 = n2;this.sum = n1 + n2;}}public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {List<List<Integer>> result = new ArrayList<>();int heapSize = nums1.length * nums2.length;HeapNode[] heap = new HeapNode[heapSize];// 建小根堆int p = 0;for (int n1 : nums1) {for (int n2 : nums2) {heap[p++] = new HeapNode(n1, n2);}}for (int i = heapSize - 1; i >= 0; i--) // 自下向上建堆 可證復雜度為O(n)heapify(heap, i, heapSize);// Top kfor (int i = 0; i < k && i < heap.length; i++) {ArrayList<Integer> pair = new ArrayList<>();pair.add(heap[0].n1);pair.add(heap[0].n2);result.add(pair);// 堆調整swap(heap, 0, --heapSize);heapify(heap, 0, heapSize);}return result;}public void heapify(HeapNode[] heap, int i, int size) {int left = i * 2 + 1;while (left < size) {int mini = left + 1 < size && heap[left + 1].sum < heap[left].sum ? left + 1 : left; // 左右孩子較小者的下標mini = heap[mini].sum < heap[i].sum ? mini : i; // 兩個孩子與父節點較小者的下標if (mini == i) break; // 不需要交換的情況swap(heap, mini, i);i = mini; // 更新i使其下沉left = 2 * i + 1;}}private void swap(HeapNode[] heap, int i, int j) {HeapNode tmp = heap[i];heap[i] = heap[j];heap[j] = tmp;} }總結
以上是生活随笔為你收集整理的leetcode 373. Find K Pairs with Smallest Sums | 373. 查找和最小的K对数字(小根堆)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 131. Palind
- 下一篇: leetcode 838. Push D