see*_*ker 5 java priority-queue java-8
我试图解决这个运动,这里是我的解决方案.它基本上保存了一个树映射,以将相同的veritical偏移处的节点映射到一个键.并且当使用节点处的值在同一(水平级别)存在多个键时,使用优先级队列来分割关系.
public List<List<Integer>> verticalTraversal(TreeNode root) {
Map<Integer, PriorityQueue<Node>> map = new TreeMap<>();
List<List<Integer>> out = new ArrayList<>();
if(root == null)
return out;
Queue<Node> q = new LinkedList<>();
Node r = new Node(root, 0, 0);
q.add(r);
while(!q.isEmpty()) {
Node curr = q.remove();
int x = curr.x;
int y = curr.y;
PriorityQueue<Node> pq = map.getOrDefault(y, new PriorityQueue<Node>((a,b) ->(a.x == b.x? a.t.val - b.t.val: a.x - b.x)));
pq.add(curr);
map.put(y,pq);
if(curr.t.left!=null){
Node left = new Node(curr.t.left, x+1, y-1);
q.add(left);
}
if(curr.t.right!=null){
Node right = new Node(curr.t.right, x+1, y + 1);
q.add(right);
}
}
for (Map.Entry<Integer, PriorityQueue<Node>> entry : map.entrySet()){
PriorityQueue<Node> pq = entry.getValue();
List<Integer> vals = new ArrayList<>();
for (Node pqNode: pq){
vals.add(pqNode.t.val);
}
out.add(new ArrayList<Integer>(vals));
}
return out;
}
class Node {
TreeNode t;
int y;
int x;
Node(TreeNode t, int x, int y) {
this.t = t;
this.x = x;
this.y = y;
}
}
Run Code Online (Sandbox Code Playgroud)
}
要清楚这里我认为问题出在哪里
PriorityQueue<Node> pq = map.getOrDefault(y, new PriorityQueue<Node>((a,b) ->(a.x == b.x? a.t.val - b.t.val: a.x - b.x)));
Run Code Online (Sandbox Code Playgroud)
当a.xisnt等于时,我得到了预期的顺序,b.x但它们似乎并不val等于它们相等的时候.
这是失败的测试用例
实际:[ [7,9],[5,6],[0,2,4],[1,3],[8]]预期:[[ 9,7],[5,6],[0 1,2,4],[1,3],[8]]
你做错的是你迭代优先级队列的元素而不是轮询它。
PriorityQueue#iterator()的文档明确指出:
返回对此队列中元素的迭代器。迭代器不以任何特定顺序返回元素。
而不是写作
for (Node pqNode: pq){
vals.add(pqNode.t.val);
}
Run Code Online (Sandbox Code Playgroud)
你应该使用:
Node pqNode;
while ((pqNode = pq.poll()) != null) {
vals.add(pqNode.t.val);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |