[英]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.