问题描述
考虑一个随机长度和随机正整数值的数组 A[1..n]。我们将 A 的子数组定义为 A 的一个连续段。我们将从位置 k 到位置 l(都包括在内)的子数组表示为 A[k..l]。如果 A[j] ≤ A[j + 1] 对于所有 j,其中 k ≤ j 4,A[4..7] = [4; 6; 6; 7]
是数组 A 中最长的上升。该算法不能使用任何辅助存储,例如“额外”数组执行所需的操作。我不知道如何解决这个问题,这是我最接近解决方案的方法。
class practice {
public static void ascentLength(int arr[],int size) {
int length = 0;
int index = 0;
for (int i = 0; i < size - 1; i++) {
index = i;
if (arr[0] <= arr[i + 1]) {
System.out.println(arr[i]);
length++;
}
if (arr[0] >= arr[i + 1]) {
length = 0;
}
}
System.out.println("length: " + length);
}
/* Driver program to test above function */
public static void main(String[] args) {
int arr[] = {5,3,6,4,7,5};
int n = arr.length;
ascentLength(arr,n);
}
}
解决方法
我立即注意到了几个错误。
在 if
表达式中,您总是将数组的第一个元素与下一个元素进行比较。应该是数组当前元素和下一个元素的比较。
count
变量未在任何地方声明。 count
变量的用途是什么?
在第二个 if
块中,在将长度分配为零之前,您没有将长度存储在单独的变量中。
Tracing
代码和为数组绘制 figures
是了解您的程序在做什么的好方法。
int arr[] = {5,3,6,4,7,5};
int maxLength = 0,count = 0;
for(int i = 0; i < arr.length - 1; i++){
if(arr[i + 1] < arr[i]){
count = 0;
}else{
count++;
if(count > maxLength){
maxLength = count;
}
}
}
System.out.println(maxLength + 1);
最后添加了 1
,因为我们不能为它自己 compare
一个数字。
您需要使用分离变量跟踪当前上升和最长上升的大小。在给定的迭代中,您要么开始新的上升,要么继续现有的上升。为了简化迭代,我们可以预先处理一些特殊情况(即空数组、空数组或单元素数组)。
public int maxAscentLength(int[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
if (arr.length == 1) {
return 1;
}
// the largest ascent so far
int maxLength = 0;
// length of current ascent - init 1 because 1st element is assumed
int currLength = 1;
// start iteration from 1 rather than 0 because 1st element is assumed
for (int index = 1 ; index < arr.length ; index++) {
if (arr[index-1] <= arr[index]) {
// continue ascent
++currLength;
} else {
// end ascent
maxLength = Math.max(maxLength,currLength);
currLength = 1;
}
}
return Math.max(maxLength,currLength);
}