Efficiently get sorted sums of a sorted list

后端 未结 8 2168
小蘑菇
小蘑菇 2021-02-18 16:50

You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-18 17:18

    In SQL:

    create table numbers(n int not null)
    insert into numbers(n) values(1),(1), (2), (2), (3), (4)
    
    
    select distinct num1.n+num2.n sum2n
    from numbers num1
    inner join numbers num2 
        on num1.n<>num2.n
    order by sum2n
    

    C# LINQ:

    List num = new List{ 1, 1, 2, 2, 3, 4};
    var uNum = num.Distinct().ToList();
    var sums=(from num1 in uNum
            from num2 in uNum 
            where num1!=num2
            select num1+num2).Distinct();
    foreach (var s in sums)
    {
        Console.WriteLine(s);
    }
    

提交回复
热议问题