迭代通過每個連續的數組並跟蹤最高連續總和在哪裏以及什麼位置以及第二高連續總和在哪裏以及什麼位置,並隨着它們獲得更高值而更新它們。
如果使用int
來存儲總和,則需要使用long
將連續的總和存儲爲加上兩個int
。
public class SecondLargest {
public static int findSecondLargestConsecutiveSum(final int[] array){
if (array == null)
throw new IllegalArgumentException("Cannot find consecutive sum in a null array");
if (array.length < 3)
return -1;
long largest = Long.MIN_VALUE;
long secondLargest = Long.MIN_VALUE;
int largestPos = -1;
int secondLargestPos = -1;
long sum;
for (int i = 0; i < array.length - 1; ++i)
{
sum = array[i] + array[i+1];
if (sum > largest) {
secondLargest = largest;
secondLargestPos = largestPos;
largest = sum;
largestPos = i;
}
else if (sum < largest && sum > secondLargest){
secondLargest = sum;
secondLargestPos = i;
}
}
return secondLargestPos;
}
public static String formatSecondLargest(final int[] array){
final int pos = findSecondLargestConsecutiveSum(array);
if (pos == -1)
return "Array does not have a second largest consecutive sum.";
return String.format("%d by elements %d,%d at position %d", (long) array[pos] + (long) array[pos+1], array[pos], array[pos+1], pos);
}
public static void main(final String[] args){
System.out.println(formatSecondLargest(new int[]{ 1,6,2,3,8 }));
System.out.println(formatSecondLargest(new int[]{ 1,6,2,3,8,3 }));
System.out.println(formatSecondLargest(new int[]{ Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE }));
System.out.println(formatSecondLargest(new int[]{ Integer.MIN_VALUE+1, Integer.MIN_VALUE, Integer.MIN_VALUE+2 }));
}
}
輸出:
8 by elements 6,2 at position 1
8 by elements 6,2 at position 1
Array does not have a second largest consecutive sum.
-4294967295 by elements -2147483647,-2147483648 at position 0
來源
2016-02-06 10:42:21
MT0
您必須在每個階段存儲變量中max和secondmax的位置,以便能夠在最後顯示元素。 –
你爲什麼使用計數器變量? – Nishant123
對於int [] {Integer.MIN_VALUE,Integer.MIN_VALUE + 1,Integer.MIN_VALUE + 2}' – MT0