【问题标题】:How can i optimise this function (beginner ) JAVA我怎样才能优化这个功能(初学者)JAVA
【发布时间】:2020-10-22 17:12:07
【问题描述】:

我有这个功能,我需要对其进行优化,以减少运行时间:

public static int recherche(int cherche, int[] t) {
    int srch = 0;
    int tmp=0;
    boolean result = false;
    for (int i=0; i<t.length ; i++) {
        if (t[i]== cherche && result == false) {
            tmp++;
            srch = i;
            result=true;
        }
    }       
    if (tmp!=0) { 
        return srch ;
    }
    else { 
        return -1;
    }
}

我也不能使用任何库工具。

【问题讨论】:

  • 请添加对这个程序试图做什么、输入是什么以及预期结果是什么的描述。是什么让你觉得它花了太长时间?如果您只是在寻找第一个匹配项,那么您希望在找到匹配项后跳出 for 循环。
  • 是的,很抱歉没有描述,所以这是在t中搜索cherche第一次出现的索引,如果没有找到则返回-1。这也是一个课堂练习,我们得到一个函数,表示它在图表中所花费的时间。

标签: java arrays performance


【解决方案1】:

如果我正确理解您的方法,您正在搜索数组t 中第一次出现cherche 的索引,如果未找到则为-1。

您的代码的问题是,即使您已经找到该条目,您也会继续循环。最好立即打破循环。您也不需要额外的变量。

public static int recherche(int cherche, int[] t) {
    int srch = -1;
    for (int i = 0; i < t.length; i++) {
        if (t[i] == cherche) {
            srch = i;
            break;
        }
    }       
    return srch;
} 

如果这仍然太慢,您可以尝试存储排序的数据或创建某种索引。

如果你有一个列表而不是一个数组,你可以使用indexOf 方法,但我不认为它对于未排序的数据会更快。 它将始终为O(n),因为在最坏的情况下您必须检查所有数组值。

P.S:请考虑使用更好的变量名。我不知道tcherche 是什么。

【讨论】:

  • 看来“cherche”是法语中“seek”的意思。
  • 感谢您的帮助,找到索引时爆发大大减少了时间。也很抱歉变量名,第一次来这里。
【解决方案2】:

在 Java 中无法使用此函数进行真正的优化。如果您知道数组t 已排序,则可以使用二进制排序。

我稍微清理了你的代码

public static int recherche(int cherche, int[] t) {
    for (int i = 0; i < t.length; i++) {
        if (t[i] == cherche) {
            return i;
        }
    }

    return -1;
}

【讨论】:

    【解决方案3】:

    您可以做的优化是在找到结果后立即返回结果并删除冗余变量。

    public static int research(int searched, int[] t) {
        for (int i=0; i < t.length ; i++) {
            if (t[i] == searched) {
                return i;
            }
        }
        return -1;
    }
    
    

    【讨论】:

      猜你喜欢
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多