[英]Java: Recursively Finding the minimum element in a list
我将以说这是家庭作业为开头。 我只是在寻找一些指示。 我一直在为这个而绞尽脑汁,对于我的一生,我只是不明白。 我们被要求在列表中找到最小的元素。 我知道我在这里需要一个子列表,但是之后我不确定。 任何指针都很棒。 谢谢。
/** Find the minimum element in a list.
*
* @param t a list of integers
*
* @return the minimum element in the list
*/
public static int min(List<Integer> t) {
if (t.size() == 1){
return t.get(0);
}
else{
List<Integer> u = t.subList(1, t.size());
递归算法的要点是必须通过返回值或其他参数来完成所有必须计算的事情。 您不应在递归步骤的本地调用之外包含任何内容。
由于必须找到最小元素,因此应注意以下几点:
通过考虑这些因素,应该很容易实现。 特别是因为递归算法具有真正类似于其算法描述的便利。
您需要找到应用于列表的功能min和应用于子列表的功能min之间的关系。
min([abcde ...])= f(a,min([bcde ...])))
现在,您只需要找到函数f。 一旦有了关系,就可以轻松实现。 祝好运。
从最一般的意义上讲,递归是一个基于分解工作的概念,然后将较小的工作分派给自己的副本。 为了使递归正常工作,您需要三件事:
在您的情况下,您正在尝试创建对列表进行操作的min
函数。 您的想法是正确的,您可以通过使列表每次变小(以第一个元素为子列表)来减少(分解)工作。 正如其他人提到的那样,该想法将是对照“列表的其余部分”检查第一个元素(刚刚删除的元素)。 好了,这就是信仰突飞猛进的地方。在这一点上,您可以“假设”您的min
函数将在子列表上工作,而只需在子列表上进行函数调用(递归调用)。 现在,您必须确保所有呼叫都将返回(即,确保不会永远递归)。 这就是您的基本案例的来源。如果列表大小为1,则唯一元素是列表中最小的元素。 无需再次致电min
,只需返回即可(原始帖子中已经包含了该部分)。
到这里,在方法中尝试一下:
public static Integer minimum(List<Integer> t) {
int minInt;
if (t.size() == 1) {
return t.get(0);
} else {
int first = t.get(0);
List<Integer> u = t.subList(1, t.size());
minInt = Math.min(first, u.get(0));
minInt = IntegerList.minimum(u);
}
return minInt;
}
希望这可以解决您的问题。
/**
* The function computes the minimum item of m (-1 if m is empty).
* @param m: The MyList we want to compute its minimum item.
* @return: The minimum item of MyList
*/
public int minimum(MyList<Integer> m){
int res = 0;
int e0 = 0;
int e1 = 0;
// Scenarios Identification
int scenario = 0;
// Type 1. MyLyst is empty
if(m.length() == 0) {
scenario = 1;
}else {
// Type 2. MyLyst is not empty
scenario = 2;
}
// Scenario Implementation
switch(scenario) {
// If MyLyst is empty
case 1:
res = -1;
break;
// If there is 1 or more elements
case 2:
//1. Get and store first element of array
e0 = m.getElement(0);
//2. We remove the first element from MyList we just checked
m.removeElement(0);
//3. We recursively solve the smaller problem
e1 = minimum(m);
//4. Compare and store results
if(e0 < e1) {
res = e0;
}
else {
res = e1;
}
//5. Return removed element back to the array
m.addElement(0, e0);
break;
}
//6. Return result
return res;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.