Java:递归查找列表中的最小元素 [英] Java: Recursively Finding the minimum element in a list

查看:351
本文介绍了Java:递归查找列表中的最小元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在前面说这是作业。我只是在寻找一些指针。我一直用这个来绞尽脑汁,而对于我的生活,我只是没有得到它。我们被要求在列表中找到最小元素。我知道我需要一个子列表,但在那之后我不确定。任何指针都会很棒。谢谢。

I will preface this by saying it is homework. I am just looking for some pointers. I have been racking my brain with this one, and for the life of me i am just not getting it. We are asked to find the minimum element in a list. I know i need a sublist in here, but after that i am not sure. any pointers would be great. thanks.

/** 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());


推荐答案

在最一般意义上,递归是一个基于概念的概念分解工作,然后将较小的工作委托给自己的副本。对于递归工作,您需要三件事:

In the most general sense, recursion is a concept based on breaking down work, and then delegating the smaller chunk of work to a copy of yourself. For recursion to work, you need three main things:


  1. 工作细分。你如何让每一步更简单?

  2. 递归调用。在某些时候,你的函数必须调用自己,但是工作更少。

  3. 基本情况。什么是停止递归过程的(通常是微不足道的)结束案例?

在您的情况下,您正在尝试创建一个在列表上运行的函数 min 。你认为你可以通过每次缩小一个列表(第一个元素的子列表)来减少(分解)你的工作是正确的。正如其他人所提到的那样,我们的想法是检查第一个元素(你刚刚取消)与列表的其余部分。好吧,这里是信仰的飞跃。此时,您可以假设您的 min 函数将在子列表上运行,并且只需对其进行函数调用子列表(递归调用)。现在你必须确保你的所有电话都会返回(即确保它不会永远递归)。这就是你的基础案例的来源。如果你的列表大小为1,那么唯一的元素就是列表中最小的元素。无需再次拨打 min ,只需返回(原始帖子中已有的部分)。

In your case, you're trying to create a function min that operates on a list. You're correct in thinking that you could somehow reduce (breakdown) your work by making the list one smaller each time (sublist out the first element). As others have mentioned, the idea would be to check the first element (which you just pulled off) against the "rest of the list". Well here's where the leap of faith comes in. At this point, you can "assume" that your min function will work on the sublist, and just make a function call on the sublist (the recursive call). Now you have to make sure all your calls will return (i.e. make sure it will not recurse forever). That's where your base case comes in. If your list is of size 1, the only element is the smallest of the list. No need to call min again, just return (that part you already have in your original post).

这篇关于Java:递归查找列表中的最小元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆