【问题标题】:Time complexity optimisation of a "nested for loop" method“嵌套for循环”方法的时间复杂度优化
【发布时间】:2018-05-09 18:33:40
【问题描述】:

我试图在整数的零索引数组中找到两个相等元素的索引之间的最大差异。

我的 for 循环目前看起来像这样,具有“嵌套 for 循环”结构 这意味着它的时间复杂度是 O(N^2)。

是否有可能将其时间复杂度降低到 O(N * log(N)) 或更低?

public static Integer solution(Integer[] arr) {
    Integer l = arr.length;
    int result = 0;
    for (int i = 0; i < l; i++) {
        for (int j = 0; j < l; j++) {
            if (arr[i] == arr[j]) {
                result = Math.max(result, Math.abs(i - j));
            }
        }
    }
    return result;
}

【问题讨论】:

标签: java for-loop


【解决方案1】:

我假设您正在尝试查找数组中两个相同数字索引的最大差异。您不需要遍历整个数组 2 次。内部循环可以简单地以i 结束,这将大大降低复杂性。

public static int solution(int[] arr) {
  int l = arr.length;
  int result = 0;
  for (int i = 0; i < l; i++) {
    for (int j = 0; j < i; j++) {
    if (arr[i] == arr[j]) {
        result = Math.max(result, Math.abs(i - j));
    }
    }
  }
  return result;
}

复杂度应该是 O(N * log(N))。

【讨论】:

  • 嗯,简单有效。感谢您分享您的代码。
  • 不客气!请考虑投票并将其标记为您问题的答案
猜你喜欢
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 2019-04-28
  • 2021-02-15
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多