c# - 查找整数列表中倒数第二大的元素 C#

标签 c# .net

我有一个

list<int> input = //from db of one million records

100 万 条记录。

虽然我知道使用 input.OrderByDescending().Skip(1).Take(1) 可以解决问题,但是如果我有 100 万条记录,那么使用OrderBY.

在这种情况下,当我们有更多记录时,哪种解决方案是最好的?

最佳答案

在跟踪 max 以及 max2 的同时扫描列表,您将得到 O(N)O (N * log(N)) 时间复杂度:

  // Maximum value
  int max  = Math.Max(input[input.Count - 1], input[input.Count - 2]);
  // Second greatest   
  int max2 = Math.Min(input[input.Count - 1], input[input.Count - 2]);

  // i >= 0: Comparing with 0 is slightly faster then with Count
  for (int i = input.Count - 3; i >= 0; --i) {
    int v = input[i];

    if (v >= max) {
      max2 = max;
      max = v; 
    }
    else if (v > max2) 
      max2 = v;
  }

编辑:如果重复应该被忽略(见下面的评论),因此[1, 2, 3, 4, 4, 4, 4] 应该是 3,而不是 4:

  // Maximum value
  int max = int.MinValue;
  // Second greatest   
  int max2 = int.MinValue;

  // i >= 0: Comparing with 0 is slightly faster then with Count
  for (int i = input.Count - 1; i >= 0; --i) {
    int v = input[i];

    if (v > max) {
      max2 = max;
      max = v;
    }
    else if (v > max2 && v != max)
      max2 = v;
  }

关于c# - 查找整数列表中倒数第二大的元素 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49747431/

相关文章:

c# - Convert.ChangeType 快捷方式吗?

c# - DataContractSerializer 如何写入私有(private)字段?

c# - 为什么 foreach(var i in array2D) 适用于多维数组?

.net - WPF 数据网格样式

c# - 如何从 WCF 服务引用 WCF 客户端而不更改后者的绑定(bind)?

c# - 使用Linq解析出XML同级节点-C#

c# - 在纹理上调用 Resources.Load 不起作用

c# - 模型中双向加密属性的 getter/setter

c# - 异步/等待异常处理模式

c# - 如何获取 URL 路径中的子目录?