15、leetcode翻转二叉树、最小的k个数

226. 翻转二叉树

翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
输出:
     4
   /   \
  7     2
 / \   / \
9   6 3   1

备注:

这个问题是受到 Max Howell 的 原问题 启发的 :

谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。

我的答案

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
        Stack<TreeNode> stack = new Stack();
        TreeNode temp=null,next = root;
        do{
            temp = next.left;
            next.left = next.right;
            next.right = temp;
            if(next.left!=null){
                if(next.right!=null){
                    stack.add(next.right);
                }
                next = next.left;
            }else if(next.right!=null){
                next = next.right;
            }else{
                if(stack.isEmpty()){
                    break;
                }
                next = stack.pop();
            }
        } while(!stack.isEmpty() || next.left!=null || next.right!=null);
        return root;
    }
}

剑指Offer 40. 最小的k个数

输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。

示例 1:

输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]

示例 2:

输入:arr = [0,1,2,1], k = 1
输出:[0]

限制:

0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000

我的答案

使用的优先队列

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if(k==0){
            return new int[0];
        }
         int[] res = new int[k];
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for(int i=0;i<k;i++) {
        	pq.add(-arr[i]);
        }
        for(int i=k;i<arr.length;i++) {
        	if(-arr[i]>pq.peek()) {
        		pq.poll();
        		pq.add(-arr[i]);
        	}
        }
        for(int i=0;i<k;i++) {
        	res[i] = -pq.poll();
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值