You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多整数列表比较:如何筛选含最高数对及优先级的列表

问题描述

现有三个整数列表:

List<int> list1 = {10, 8, 10, 7, 4, 14, 3};
List<int> list2 = {10, 8, 10, 7, 4, 13, 3};
List<int> list3 = {10, 8, 12, 12, 4, 13, 3};

需要按以下规则选出优先级最高的列表:

  • 优先比较最高数对的数值:数对指列表中重复出现至少两次的元素,取数值最大的那个数对。比如list1、list2的最高数对是10(出现两次),list3的最高数对是12(出现两次),所以list3优先级更高。
  • 若最高数对的数值相同,则比较剩余元素的最大值:比如list1和list2数对都是10,list1剩余元素的最大值是14,比list2的13大,所以list1优先级高于list2。

另外你写的降序排序方法存在问题:它仅生成了排序后的序列,没有修改原列表也未返回结果,导致排序后的序列无法用于后续逻辑。

解决方案

第一步:修正排序方法

先把排序方法改成能返回排序后列表的形式,或者直接修改原列表:

// 方法1:返回排序后的新列表
List<int> OrderList(List<int> listToOrder)
{
    return listToOrder.OrderByDescending(x => x).ToList();
}

// 方法2:直接修改传入的列表
void OrderList(List<int> listToOrder)
{
    listToOrder.Sort((a, b) => b.CompareTo(a));
}

第二步:提取每个列表的比较指标

对每个排序后的列表,计算两个关键指标:

  1. 最高数对数值:因为列表是降序排列,遍历过程中第一个出现重复的元素就是数值最大的数对,直接取值即可。
  2. 剩余元素最大值:如果存在数对,过滤掉所有该数对的元素后取剩余元素的最大值;如果没有数对,直接取列表最大值。

第三步:实现完整比较逻辑

把每个列表和对应的指标封装后,按规则排序选出最优列表,完整示例代码如下:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> {10, 8, 10, 7, 4, 14, 3};
        List<int> list2 = new List<int> {10, 8, 10, 7, 4, 13, 3};
        List<int> list3 = new List<int> {10, 8, 12, 12, 4, 13, 3};

        var allLists = new List<List<int>> {list1, list2, list3};

        // 计算每个列表的指标并排序
        var rankedLists = allLists.Select(list => 
        {
            var sortedList = OrderList(list);
            int maxPairValue = 0;
            bool hasPair = false;
            
            // 找第一个重复元素(最高数对)
            for (int i = 0; i < sortedList.Count - 1; i++)
            {
                if (sortedList[i] == sortedList[i+1])
                {
                    maxPairValue = sortedList[i];
                    hasPair = true;
                    break;
                }
            }

            // 计算剩余元素最大值
            int remainingMax = hasPair 
                ? sortedList.Where(x => x != maxPairValue).DefaultIfEmpty(0).Max() 
                : sortedList.Max();

            return new { List = list, MaxPair = maxPairValue, RemainingMax = remainingMax };
        })
        .OrderByDescending(x => x.MaxPair)
        .ThenByDescending(x => x.RemainingMax)
        .ToList();

        // 输出优先级最高的列表
        var topList = rankedLists.First().List;
        Console.WriteLine("优先级最高的列表:");
        Console.WriteLine(string.Join(", ", topList));
    }

    static List<int> OrderList(List<int> listToOrder)
    {
        return listToOrder.OrderByDescending(x => x).ToList();
    }
}

代码说明

  • 降序排序后,第一个重复元素就是最大数对,无需遍历整个列表,提升效率。
  • 通过OrderByDescending和ThenByDescending实现两级排序,直接得到按规则优先级最高的列表。

内容的提问来源于stack exchange,提问作者reineinmyheart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:24:58