如何返回列表中的两个最高价值的总和。以最有效的方式? C#
我正在尝试通过侧重于性能的预先编写的测试。返回INT列表中两个最高数字总和的最有效方法是什么?我尝试了以下操作,根据测试,在较大列表方面还不够快:
1. list.Sort();
list.Reverse();
return list[0] + list[1];
2. return list.OrderByDescending(num => num).FirstOrDefault() + list.OrderByDescending(num => num).Skip(1).FirstOrDefault();
3. var secondHighest = list.Distinct()
.OrderByDescending(i => i)
.Skip(1)
.First();
return list.Max() + secondHighest;
I'm trying to pass a pre-written test with focus on performance. What is the most efficient way to return the sum of the two highest numbers in a List of int? I have tried the following and according to the test it wasn't fast enough when it comes to larger lists:
1. list.Sort();
list.Reverse();
return list[0] + list[1];
2. return list.OrderByDescending(num => num).FirstOrDefault() + list.OrderByDescending(num => num).Skip(1).FirstOrDefault();
3. var secondHighest = list.Distinct()
.OrderByDescending(i => i)
.Skip(1)
.First();
return list.Max() + secondHighest;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
任何直接的排序操作都将是o(n*log(n))(
orderby(discending)
,sort> sort
)最好(在随机数据上),尽管当前任务是可以在o(n)带有简单循环(假设列表中至少有2个项目,对于有2个或更少元素的情况,只需返回list.sum.sum.sum()
):值得注意的是可以在某些情况下,以
Orderby(discending)
与first(ordefault)
或可能的进行
进行 toge toke (请参阅)(请参阅(请参阅)(请参阅) a href =“ https://github.com/dotnet/corefx/pull/2401” rel =“ nofollow noreferrer”>一个, 两个,,Any straightforward sorting operation would be O(n*log(n)) (
OrderBy(Descending)
,Sort
) at best (on random data) though current task is achievable in O(n) with a simple loop (assuming there are at least 2 items in the list of course, for the case when there are 2 or less elements just returnlist.Sum()
):Also it worth noting that there can be implementation depended LINQ optimizations for some of cases like combination of
OrderBy(Descending)
with operators likeFirst(OrDefault)
or possiblyTake
(see one, two, three).好吧,我建议使用此算法:
[3,2,3,2]的输入集,它将返回6。这是O(n)时间复杂性。
对于一组[3],它将返回3。
Well, I'm proposing this algorithm:
Input set of [3, 2, 3, 2], it will return 6. This is O(n) time complexity.
For a set of [3], it will return 3.
LINQ可以是一个很好的解决方案。
LINQ can be a very good solution for it.
您可以尝试这种简单的方法:
或者
首先,它对您的列表进行排序,然后将其倒转,现在您已经进行了降序的列表,而不是采用2个最高元素并汇总它们。
You can try this simple way:
or
At first, it sorts your list, then reverses it , now you have descending sorted list , than it will take 2 highest elements and aggregate them .