更新时间:2022-03-15 21:41:16
由于列表的长度是均匀的,并且您要将其整洁地切成两半,因此我建议使用以下方法(首先使用伪代码):
Since your list has an even length, and you're cutting it cleanly in half, I recommend the following (psuedocode first):
slow
和fast
.slow
一次遍历列表中的一个元素,fast
一次遍历两个元素.slow
将每个元素添加到累加器变量,而fast
向前移动.fast
指针到达列表的末尾时,slow
指针将只有元素数量的一半,因此它位于数组的中间.slow
跳过+剩余元素.这应该是两个列表,整齐地切成两半.slow
and fast
.slow
steps through the list one element at a time, fast
steps two elements at a time.slow
adds each element to an accumulator variable, while fast
moves foward.fast
pointer reaches the end of the list, the slow
pointer will have only stepped half the number of elements, so its in the middle of the array.slow
stepped over + the elements remaining. This should be two lists cut neatly in half.上面的过程需要遍历整个列表,并在O(n)时间内运行.
The process above requires one traversal over the list and runs in O(n) time.
由于这是家庭作业,因此我不会给出完整的答案,只是为了让您起步,这是将清单切成两半的步骤:
Since this is homework, I won't give a complete answer, but just to get you partway started, here's what it takes to cut the list cleanly in half:
let cut l =
let rec cut = function
| xs, ([] | [_]) -> xs
| [], _ -> []
| x::xs, y::y'::ys -> cut (xs, ys)
cut (l, l)
请注意x::xs
步骤1元素,y::y'::ys
步骤2.
Note x::xs
steps 1 element, y::y'::ys
steps two.
此函数返回列表的后半部分.修改它非常容易,因此它也返回列表的前半部分.
This function returns the second half of the list. It is very easy to modify it so it returns the first half of the list as well.