将一个int列表添加到一个int列表中

问题描述 投票:-1回答:1

我正在尝试leetCode的模拟测试..

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

可以有人pelase建议我哪里出错了......萎靡不振

Line 8: Char 30: error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<int, int>>' to 'System.Collections.Generic.List<int>' (in Solution.cs)
Line 12: Char 16: error CS0266: Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>'. An explicit conversion exists (are you missing a cast?) (in Solution.cs)

public class Solution {
    public IList<IList<int>> ThreeSum(int[] nums) {

        List<List<int>> myList = new List<List<int>>();

        foreach(var i in nums)
        {
        List<int> triplets = nums.GroupBy(x => x).Where(y => y.Count() >= 3).ToList();
            myList.Add(triplets);
        }

        return myList;
    }
}

SO ThreeSum是列表列表的接口。所以我创建了我的返回对象myList迭代nums中的每个项目创建一个List三元组,获取值,并将它们添加到myList。我知道问题是因为int列表的列表,我正在为此添加一个列表。三元组应该是一个int列表列表。我猜那么Q是如何用一个列表填充一个int列表列表?

c# list foreach
1个回答
0
投票

第一个错误是因为for循环中的List与表达式返回的类型不同。 GroupBy返回List<System.Linq.IGrouping<int, int>>,因此可以通过更改表达式以返回整数列表或更改类型以匹配返回值(List<System.Linq.IGrouping<int, int>>)来解决此问题。我认为改变表达式可以更好地查看你正在做的事情。第二个错误是因为您的方法返回类型与您返回的类型不同。您的声明建议您将返回IList<IList<int>>,但myList对象是List<List<int>>。这些需要匹配,因此要么更改方法声明,要么更改myList对象类型,以便它们匹配。我猜你的声明可能是正确的所以我会改变myList对象来匹配。

© www.soinside.com 2019 - 2024. All rights reserved.