【问题标题】:Remove binary search [duplicate]删除二分搜索[重复]
【发布时间】:2016-11-11 13:17:18
【问题描述】:

我正在研究一种 Path 方法,该方法返回从给定节点到具有给定值的键的节点的路径。我的代码返回正确的数字,但它们在括号内。如何去掉支架?

 private boolean pathhelp(Node n, int val, ArrayList<Integer> lst){
    if(n == null){
        return false;
    }else if(val < n.key){
        lst.add(n.key);
        return pathhelp(n.left, val, lst);
    }else if(val > n.key ){
        lst.add(n.key);
        return pathhelp(n.right, val, lst);
    }else{
        lst.add(n.key);
        return true;
    }
  }
   public String path(Node node, int value) {
    ArrayList<Integer> path = new ArrayList<Integer>();

    if(pathhelp(root,value,path) == true ){
        System.out.println(path);
        String p = "";
        //build p from path list

        return p;
    }else{
        return "";
    }
 }
  }

实际输出为:

[6, 5, 1, 4]

但它应该是:

6, 5, 1, 4

【问题讨论】:

  • 既然 path 是一个数组,为什么不直接循环抛出它并打印出来呢?然后你就可以控制它的样子了。
  • 我试过了,我得到了语法错误@imtheman

标签: java


【解决方案1】:

例如类似的东西(使用 Java 8 Streams):

import java.util.*;
import java.util.stream.Collectors;

class Scratch {

    public static void main(String[] args) {
        ArrayList<Integer> path = new ArrayList<Integer>();
        path.add(1);
        path.add(2);

        String asString = path.stream()
                                    .map(Object::toString)
                                    .collect(Collectors.joining(", "));

        System.out.println(asString);
    }
}

你也可以使用 Guava 的Joiner

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    相关资源
    最近更新 更多