使用仅列表作为参数的递归方法,找到具有重复元素的传染子阵列的最大长度
问题: 找到具有重复元素的传染子阵列的最大长度。
例如:[1 2 2 2 3 3 5 1 8]
- 答案是3,因为2重复3次是最大重复时间。[1 2]
- 答案是1[1 2 2 3 3]
- 答案为2
,但是递归函数应仅具有列表作为参数。int findmaxContagiousRepeatEdlength(list< integer> list)
我尝试过的内容:
class Answer
{
public static int findMaxContagiousRepeatedLength(List<Integer> nums, int currentCount, int latestNumber)
{
if (nums.isEmpty())
return 0;
if (nums.get(0) == latestNumber) {
return Math.max(currentCount+1, findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), currentCount+1, nums.get(0)));
} else {
return findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), 1, nums.get(0));
}
}
public static void main(String[] args)
{
Integer[] nums = { 1,2,1,1,1,1,1,2,3,2,3,1,2,2};
System.out.println("Max length: " +
findMaxContagiousRepeatedLength(Arrays.asList(nums), 0, nums.length == 0 ? -1 : nums[0]));
}
}
上述确实有效,但不符合参数限制的要求。 请帮助我弄清楚是否有可能有一个解决方案,其中递归功能只有列表作为参数。
Problem:
Find the maximum length of contagious subarray with repeated elements.
eg:[1 2 2 2 3 3 5 1 8]
- answer is 3 since 2 repeated 3 times is the max repeated times.[1 2]
- answer is 1[1 2 2 3 3]
- answer is 2
But the recursive function should only have list as the argument.int findMaxContagiousRepeatedLength(List<Integer> list)
What I've tried:
class Answer
{
public static int findMaxContagiousRepeatedLength(List<Integer> nums, int currentCount, int latestNumber)
{
if (nums.isEmpty())
return 0;
if (nums.get(0) == latestNumber) {
return Math.max(currentCount+1, findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), currentCount+1, nums.get(0)));
} else {
return findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), 1, nums.get(0));
}
}
public static void main(String[] args)
{
Integer[] nums = { 1,2,1,1,1,1,1,2,3,2,3,1,2,2};
System.out.println("Max length: " +
findMaxContagiousRepeatedLength(Arrays.asList(nums), 0, nums.length == 0 ? -1 : nums[0]));
}
}
The above does work, but doesn't meet the requirement of argument restriction.
Please help me figure out if it's possible to have a solution where recursive function only have list as the argument.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最佳解决方案
使用您的功能
并制作第二个功能,该功能使用默认参数调用您的函数
,现在您可以调用第二个功能,该功能将带有默认参数的第一个函数!
Best solution
Use your Function
and make a second Function which calls your function with default parameters
Now you can call the second function which calls the first function with default parameters!
首先,只需浏览列表即可最好地解决此问题。
但是,如果您必须将递归与
list&lt; integer&gt;
作为唯一可以使用以下参数:First, this problem is best solved by just going through the list.
But if you must use recursion with
List<Integer>
as the only parameter you may use the below:如果允许您(暂时)修改列表,则以下方法也将起作用:
If you're allowed to (temporarily) modify the list, the below approach would also work: