leetcode 373. Find K Pairs with Smallest Sums
2016-07-07 20:02
597 查看
原题链接
原题链接解题思路
解这道题花了一点时间。发现用PriorityQueue来解决这问题就变得简单了。先用一个类封装了row,col,val,并实现compareTo方法,方便用PriorityQueue排序。
先将最小值0,0,nums1[0]+nums2[0]压入优先队列。
算法思想是bfs,从优先队列取出最小值并加入List res,很明显最接近这个值的要么(row+1,col),要么(row,col+1)。将两个值压入优先队列。
返回res。
解题代码
public class Solution { public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) { int x = nums1.length;int y = nums2.length; Queue<Pair> q = new PriorityQueue<>(); List<int[]> res = new ArrayList<>(); if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0 || k == 0) { return res; } boolean[][] visited = new boolean[x][y]; q.offer(new Pair(0,0,nums1[0]+nums2[0])); visited[0][0] = true; for(int i = 0;i<k;i++){ if(q.isEmpty()) break; Pair p = q.poll(); res.add(new int[]{nums1[p.row],nums2[p.col]}); if(p.row < nums1.length - 1 && !visited[p.row+1][p.col]){ q.offer(new Pair(p.row + 1,p.col,nums1[p.row+1]+nums2[p.col])); visited[p.row+1][p.col] = true; } if(p.col < nums2.length-1 && !visited[p.row][p.col+1]){ q.offer(new Pair(p.row,p.col+1,nums1[p.row]+nums2[p.col+1])); visited[p.row][p.col+1] = true; } } return res; } } class Pair implements Comparable<Pair>{ int row; int col; int val; Pair(int r,int c,int v){ this.row = r; this.col = c; this.val = v; } @Override public int compareTo(Pair pair){ return this.val - pair.val; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解