小编Gök*_*ğan的帖子

if else vs java中的switch性能

我想知道使用if语句或switch之间是否存在任何效率差异.例如:

if(){
//code
}
else if(){
//code
}
else{
//code
}
Run Code Online (Sandbox Code Playgroud)

我相信程序需要去检查所有if语句,即使第一个if语句是真的.

switch(i){

case 1:
//code
break;
case 2:
//code
break;
Run Code Online (Sandbox Code Playgroud)

但是在交换机中,有一个break命令.我接近了吗?如果没有,你能解释一下它们之间的效率差异吗?

java if-statement switch-statement

5
推荐指数
1
解决办法
6501
查看次数

编写反向字符串O(N)时间复杂度和O(N)空间复杂度的程序

我被要求解决低于N ^ 2时间复杂度和O(N)空间复杂度的以下问题:

为以下情况编写程序反向字符串:

输入: - "Hello World"输出: - "olleH dlroW"

我试图弄清楚它,但无论我尝试什么,我都无法想出时间复杂度低于N ^ 2,我的代码可以在下面看到,你有什么建议我怎么能想出来线性时间的解决方案?

注意:不允许使用内置方法

 public static String stringReverser(String str) {
        if (str == null || str.isEmpty()) {
            throw new IllegalArgumentException();
        }
        if (str.length() < 2) {
            return str;
        }
        String[] strArr = str.split(" ");
        StringBuffer newHolder = new StringBuffer();
        for (int i = 0; i < strArr.length; i++) {
            int j = 0;
            int len = strArr[i].length();
            char[] newCharStr = strArr[i].toCharArray();
            while (j < len) {
                char temp = …
Run Code Online (Sandbox Code Playgroud)

java string algorithm reverse swap

3
推荐指数
1
解决办法
2450
查看次数

找到字典中最常见的三个单词

问题是在字典中找到三个最常见的单词.我已经提出了下面的代码,但由于某些原因它不起作用(我的意思是当我尝试在eclipse中运行它时,它直接导致我调试页面,虽然我没有在编译器屏幕上得到任何错误),我调试后找不到原因.你能帮我找到问题吗?

java.util.PriorityQueue.add
(未知来源)中的线程"main"java.lang.NullPointerException中的异常,
位于
generalquestions.MostCommonWords.mostCommonStringFinder(MostCommonWords.java:41)的java.util.PriorityQueue.add (未知来源).MostCommonWords.main
(MostCommonWords.java:61)

  public static Queue<Integer> mostCommonStringFinder (String document, int k){

    if (document == null){
        throw new IllegalArgumentException();
    }
    if (document.isEmpty()){
        throw new IllegalArgumentException("Document is empty");
    }   

    String [] wordHolder = document.split(" ");     

    HashMap<String, Integer> map = new HashMap<String, Integer>();


    for (String s : wordHolder){

        if (!map.containsKey(s)){
            map.put(s, 1);

        }
        else{
            int value = map.get(s);
            value++;
            map.put(s, value);
        }           
    }

    Queue<Integer> minHeap = new PriorityQueue<>();

    for ( int i = 0 ; i < k ; …
Run Code Online (Sandbox Code Playgroud)

java algorithm heap dictionary data-structures

0
推荐指数
1
解决办法
194
查看次数