繁体   English   中英

将整数列表添加到整数列表列表

[英]add a list of ints to a list of lists of ints

我正在尝试 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.

有人可以建议我哪里出错了......标记

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 列表的列表?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM