[英]How to find the location of the largest element in an array using recursion?
給定一個數組列表,列表上的元素計數使用遞歸找到最大元素的位置。
到目前為止,我能夠找到最大的元素,但是我需要該元素在數組上的位置,而不是實際值。
private int getLargestElementLoca(int[] list, int count)
{
int largestValue;
if(count == 1){
return 0;
}
int tempMax = getLargestElementLoca(list,count-1);
largestValue = Math.max(list[count-1],tempMax);
return largestValue;
}
一個想法可能是將數組遞歸分為兩部分,直到只剩下2個或1個元素。 查找兩個或一個最大值是很簡單的,然后返回它。 然后,您比較兩個返回的值並返回最大值。
遞歸很簡單,但是您應該知道如何迭代:
private int getMaxLocation(int[] array) {
int maxpos = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
maxpos = i;
}
}
return maxpos;
}
如果要通過遞歸進行此操作,則需要在其中跟蹤一些變量:
private int getMaxLocation(int[] array, int pos, int max, int maxpos) {
if (pos >= array.length || pos < 0) {
return maxpos;
} else {
int current = array[pos];
if (current > max) {
max = current;
maxpos = pos;
}
return getMaxLocation(array, ++pos, max, maxpos);
}
}
//calling this
int max = getMaxLocation(yourArray, 0, Integer.MIN_VALUE, 0);
您走在正確的道路上,但只需要一些調整即可。 我不會為您編寫代碼,但是這里有一些提示。
如果要讓函數返回索引而不是最大值,則需要更改計算返回值的方式以及遞歸使用返回值的方式。
private int getLargestElementLoca(int[] list, int count)
{
int largestValue;
if(count == 1){
return 0;
}
如果只看一個元素,即list[0]
,則list[0]
將是最大值,而0將是其索引。 因此,此處返回0是正確的。
int tempMax = getLargestElementLoca(list,count-1);
您已經重新定義了getLargestElementLoca
以便它返回一個索引,而不是最大值。 這也適用於遞歸調用,因此tempMax
將成為索引而不是值。 這意味着您不能將其直接傳遞到Math.max
。 需要進行一些調整,但請繼續閱讀。
largestValue = Math.max(list[count-1],tempMax);
Math.max
返回最大值,但這不是您想要的。 您有兩個索引, count-1
和其他索引,並且您要計算較大值的索引 。 您無法使用Math.max
做到這一點,但可以使用if
語句或條件運算符a ? b : c
a ? b : c
。 重命名變量也將很有幫助,因為它不再包含最大值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.