![](/img/trans.png)
[英]What will be the run time complexity for recursive algorithm for finding the largest number in an array. Compare it vs iterative loop code
[英]Find the largest drop between two numbers in an array. What is the time complexity of this code?
我有一个充满数字的数组。 我需要找到 2 个数字之间的最大差异,但最大的数字在数组中的最小数字之前。
public static int maximalDrop(int[] a)
例如:
对于数组5, 21, 3, 27, 12, 24, 7, 6, 4
结果将为23 (27 - 4)
对于数组5, 21, 3, 22, 12, 7, 26, 14
结果将为18 (21 - 3)
我想我是用时间复杂度O(N)
写的,我的代码可以吗? 我的代码的时间复杂度是多少? 这是我写的方法:
public static int maximalDrop(int[] a) {
int i = 0;
int temp = 0;
int result = -1;
int k = a.length - 1;
boolean finishCheckLoop = false;
while (k > i) {
if (a[i] < a[i + 1] || finishCheckLoop == true) {
i++;
finishCheckLoop = false;
} else if (a[i] >= a[k] || a[i] <= a[k]) {
if (a[k] < 0)
temp = Math.abs(a[k]) + a[i];
else if (a[k] > 0)
temp = a[i] - a[k];
result = Math.max(temp, result);
k--;
}
if (i == k) {
k = a.length - 1;
finishCheckLoop = true;
}
}
return result;
}
您的代码似乎是O(N)
,但对于该任务来说非常复杂。
一个更简单(更快)的版本:
public static int maximalDrop(int[] a) {
int maxDrop = 0;
int drop = 0;
int max = Integer.MIN_VALUE;
int cur;
for (int i = 0; i < a.length; i++) {
cur = a[i];
if (cur > max) {
max = cur;
}
drop = max - cur;
if (drop > maxDrop) {
maxDrop = drop;
}
}
return maxDrop;
}
免责声明,我不是真的写 java,所以我不确定Integer.MIN_VALUE
是否正确。
是的,您的代码的时间复杂度为O(N)
,但它不可读并且可能难以编写。
几乎我们所有人都有这种不好的倾向,在我们知道如何解决问题之前就开始编码。 这里提供的代码似乎是这种技术的产物。
要改进代码,我们应该拿起笔和纸,简单地思考。 请注意,我们需要返回从左到右的最大下降,所以有很多情况
让我们保留high
、 low
和maximalDrop
变量:
目前的数字是新低:
low
= 当前数字。maximalDrop
。当前数字是新高 - 之前的低点无关紧要。
否则 - 什么都不做。
现在很容易编码:
public static int maximalDrop(int[] a) {
if (a.length == 0) {
return -1;
}
int h = a[0], l = a[0];
int maxDrop = -1;
for (int curr : a) {
if (curr < l) {
l = curr;
maxDrop = Math.max(h - l, maxDrop);
} else if (curr > h) {
h = curr;
l = Integer.MAX_VALUE;
}
}
return maxDrop;
}
Output 示例:
System.out.println(maximalDrop(new int[]{5, 21, 3, 27, 12, 24, 7, 6, 4})); // 23
System.out.println(maximalDrop(new int[]{5, 21, 3, 22, 12, 7, 26, 14})); // 18
System.out.println(maximalDrop(new int[]{5, 6})); // -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.