TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Using Scheme to Find the Median of Two Sorted Integer Lists

42 点作者 erwald将近 4 年前

4 条评论

cousin_it将近 4 年前
Fun problem, conceptually easy but very prone to off-by-one errors. I think it&#x27;s a bit easier to implement median using kth. Also it doesn&#x27;t need recursion, one loop with fixed space usage is enough. Here&#x27;s my JS code:<p><pre><code> function kth2(a,b,k) { var ai=0,aj=a.length,bi=0,bj=b.length,d=1; while (true) { if (ai==aj) return b[bi+d*k]; if (bi==bj) return a[ai+d*k]; var m=d*(aj-ai),n=d*(bj-bi); if (k&lt;(m+n)&#x2F;2) [ai,aj,bi,bj,d,k] = [aj-d,ai-d,bj-d,bi-d,-d,m+n-1-k]; var ak=Math.floor((m+1)&#x2F;2),bk=Math.floor((n+1)&#x2F;2); if (d*a[ai+d*ak-d]&lt;d*b[bi+d*bk-d]) [ai,k] = [ai+d*ak,k-ak]; else [bi,k] = [bi+d*bk,k-bk]; } } function median2(a,b) { var n = a.length+b.length; if (n%2 == 1) return kth2(a,b,(n-1)&#x2F;2); else return (kth2(a,b,n&#x2F;2-1)+kth2(a,b,n&#x2F;2))&#x2F;2; }</code></pre>
评论 #27405017 未加载
评论 #27404858 未加载
评论 #27404449 未加载
rav将近 4 年前
My favorite problem involving Two Sorted Integer Lists is &quot;Sort X+Y&quot;: Given sorted lists X and Y, each of length N, produce the list of N^2 pair-sums in sorted order. Specifically X+Y is the set {a + b for a in X and b in Y}. It seems like you should be able to solve it without relying on a sorting algorithm, since the input lists are already sorted. However, it&#x27;s unknown if there is a faster algorithm than simply constructing X+Y directly and running a sorting algorithm.
评论 #27405493 未加载
评论 #27407029 未加载
评论 #27407026 未加载
评论 #27409820 未加载
bjornsing将近 4 年前
If the “lists” are not random access, and you know their lengths, then why not just traverse them in parallel? I find it hard to believe you can do it faster than that, and it’s super simple...
评论 #27407405 未加载
评论 #27408849 未加载
walshemj将近 4 年前
Bit surprised that this<p>&quot;Getting the median of a single sorted list is trivial: it is either the central value if the list has an odd-numbered length, or the mean of the two central values otherwise.&quot;<p>Is stated with no proof its not something I recall from collage
评论 #27404790 未加载
评论 #27405099 未加载
评论 #27405040 未加载
评论 #27405757 未加载
评论 #27405025 未加载
评论 #27405010 未加载