我正在做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
您需要创建一个自定义类,其中 count
和 number
作为字段,如下所示:
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执行提交代码的方式外,创建包装类也有利于封装。如上面的代码,您可以将 counter
和 result
封装到一个类中,以及一些必要的方法,例如测试方法 isDone
和方法 decreaseCount
。
顺便说一句,您测试了您的 helper
方法吗?这是一种递归方法,但我认为终止条件不正确。
关于java - java中将两个变量包装到一个包装类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683923/