CodingBat挑战:SameEnds流API解决方案
给定任务 sameEnds 来自 codingbat :
如果
n
数字在数组开始和结束时的数字相同,则返回true。例如,使用{5、6、45、99、13、5、6}
,对于n = 0
和n = 2,末端相同
,对于n = 1
和n = 3
。您可以假设n
在范围内0..nums.length
包含。sameEnds([5,6,6,45,99,13,5,6],1)→false sameEnds([[5,6,45,99,13,5,6],2)→true sameEnds([5,6,45,99,13,5,6],3)→false
我解决这个问题的解决方案通过了绝大多数测试,但并非全部:
public boolean sameEnds(int[] nums, int len) {
if (nums.length >= len * 2) {
for (int i = 0, j = nums.length - 1 ; i < len && len > 0; i++, j--) {
if (nums[i] != nums[j]) {
return false;
}
}
}
return true;
}
我的问题如下:
- 为了解决我的解决方案,该怎么办?
- 是否可以使用 流API 来解决此任务?
Given the task sameEnds from CodingBat:
Return true if the group of
N
numbers at the start and end of the array are the same. For example, with{5, 6, 45, 99, 13, 5, 6}
, the ends are the same forn=0
andn=2
, and false forn=1
andn=3
. You may assume thatn
is in the range0..nums.length
inclusive.sameEnds([5, 6, 45, 99, 13, 5, 6], 1) → false sameEnds([5, 6, 45, 99, 13, 5, 6], 2) → true sameEnds([5, 6, 45, 99, 13, 5, 6], 3) → false
My solution to this problem passes the vast majority of the tests, but not all of them:
public boolean sameEnds(int[] nums, int len) {
if (nums.length >= len * 2) {
for (int i = 0, j = nums.length - 1 ; i < len && len > 0; i++, j--) {
if (nums[i] != nums[j]) {
return false;
}
}
}
return true;
}
My questions are the following:
- What can be done in order to fix my solution?
- Is it possible to solve this task using Stream API ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
allMatch()
操作以便使用流实现它。该解决方案通过 codingbat 的所有测试用例:
对您的命令解决方案的解决方案可能看起来像这样:
我删除了包装,因为
nums.length&gt; = len * 2 评估为
false
,这意味着需要比较重叠的子阵列,但这并不意味着这些 subsarrays 是相等的。条件
len&gt; 0
是多余的,因为它可以保证在范围内[0,nums.length]
。变量
j
表示尾巴中的位置 subaray 已初始化为nums.length -1-(len -1)
- 最后有效的索引子阵列的长度。 循环的的所谓增量语句从
j -
更改为j ++
。You can use
allMatch()
operation in order to implement it with streams.This solution passes all test cases on CodingBat:
A fix to your imperative solution might look like this:
I removed the wrapping if condition because when
nums.length >= len * 2
is evaluated tofalse
it means that subarrays that need to be compared overlap, but it doesn't automatically mean that these subarrays are equal.Condition
len > 0
is redundant because it is guaranteed to be in the range[0,nums.length]
.Variable
j
that denotes position in the tail subarray has been initialized tonums.length - 1 - (len - 1)
- last valid index minus subarray's length. And the so-called increment statement of thefor
loop was changed fromj--
toj++
.您可以使用内置方法 arrays.quars.equals 如果您使用的是Java 9或更高:
You can use the built in method Arrays.equals if you are using Java 9 or higher: