leetcode 378. Kth Smallest Element in a Sorted Matrix 解题报告
2016-08-04 23:27
597 查看
原题链接
原题链接解题思路
这道题用BFS+优先级队列(堆)。其实这道题和我前面写的一道题解题方法一模一样。题号是373。这里就不细讲了。解题代码
public class Solution { public int kthSmallest(int[][] matrix, int k) { PriorityQueue<Num> q = new PriorityQueue<>(); int n = matrix.length; int count = 0; int res = 0; q.offer(new Num(0,0,matrix[0][0])); boolean[][] visited = new boolean ; visited[0][0] = true; while(!q.isEmpty()) { Num num = q.poll(); if(++count == k) { return num.val; } if(num.x + 1 < n && !visited[num.x + 1][num.y]) { Num tnum = new Num(num.x + 1,num.y,matrix[num.x + 1][num.y]); q.offer(tnum); visited[num.x + 1][num.y] = true; } if(num.y + 1 < n && !visited[num.x][num.y + 1]) { Num tnum = new Num(num.x,num.y + 1,matrix[num.x][num.y + 1]); q.offer(tnum); visited[num.x][num.y + 1] = true; } } return -1; } } class Num implements Comparable<Num>{ int x; int y; int val; Num(int x,int y,int val) { this.x = x; this.y = y; this.val = val; } @Override public int compareTo(Num o) { return this.val - o.val; } }
相关文章推荐
- [Leetcode] 378. Kth Smallest Element in a Sorted Matrix 解题报告
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix 解题报告
- 【leetcode】378. Kth Smallest Element in a Sorted Matrix
- 378.leetcode Kth Smallest Element in a Sorted Matrix(medium)[堆求第K小的 ]
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- 【leetcode】378. Kth Smallest Element in a Sorted Matrix【M】【88ms】
- leetcode :Binary Search:Kth Smallest Element in a Sorted Matrix(378)
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode:378 Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- [leetcode] 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode 378. Kth Smallest Element in a Sorted Matrix
- Leetcode-378. Kth Smallest Element in a Sorted Matrix
- leetcode378:Kth Smallest Element in a Sorted Matrix(medium)
- Leetcode 378. Kth Smallest Element in a Sorted Matrix
- LeetCode[378] Kth Smallest Element in a Sorted Matrix