java - java中将两个变量包装到一个包装类中

标签 java

我正在做leetcode Q 230。 问题是 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中的第 k 个最小元素。
我在谷歌上搜索了这个问题的一个解决方案,该解决方案提到将两个变量包装到一个包装类中可能会很好。我不知道如何将两个变量(数字和计数)包装在包装类中,它有什么用处?我知道Integer是int的包装类。

***better keep these two variables in a wrapper class***

private static int number = 0;
private static int count = 0;

public int kthSmallest(TreeNode root, int k) {
    count = k;
    helper(root);
    return number;
}

public void helper(TreeNode n) {
    if (n.left != null) helper(n.left);
    count--;
    if (count == 0) {
        number = n.val;
        return;
    }
    if (n.right != null) helper(n.right);
}

最佳答案

I don't know how to wrapper the two variables (number & count) in a wrapper class

您需要创建一个自定义类,其中 countnumber 作为字段,如下所示:

class KthSmallestElementWrapper<T> {
private int kth;
private T result;

public KthSmallestElementWrapper(int kth) {
    this.kth = kth;
}

public static KthSmallestElementWrapper of(int kth) {
    return new KthSmallestElementWrapper(kth);
}

public boolean isDone() {
    return kth == 0;
}

public T getResult() {
    if (result == null) {
        throw new RuntimeException("Result not found");
    }
    return result;
}

public void decreaseCount() {
    kth--;
}

public void setResult(T t) {
    this.result = t;
}
}

what is the good use of it?

除了LeeCode执行提交代码的方式外,创建包装类也有利于封装。如上面的代码,您可以将 counterresult 封装到一个类中,以及一些必要的方法,例如测试方法 isDone 和方法 decreaseCount

顺便说一句,您测试了您的 helper 方法吗?这是一种递归方法,但我认为终止条件不正确。

关于java - java中将两个变量包装到一个包装类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683923/

相关文章:

java - 为什么字符串需要不同的时间来创建?

java - 如何编写提示运行时使用 DEFAULT 值的 JPA QL 语句?

java - 这是封装派生类的好方法吗?

java - 如何使用spring实现lazy db数据获取

java - 如何在 Eclipse 中的源文件夹之间递归移动包并更新 CVS?

java - Cassandra 中的 NoHostAvailableException

Java args 命令行参数 - 尝试将文件名作为 args 中的参数传递给方法但不起作用

java - 跟踪 Swing GUI "current state"

java - EJB @Schedule 等待方法完成

java - 从数组加载 map (游戏)时出现问题