【问题标题】:Extract elements from List of List in C#从 C# 中的列表列表中提取元素
【发布时间】:2023-01-28 01:13:35
【问题描述】:

我正在尝试解决 HackerRank 练习“不可分割的子集” https://www.hackerrank.com/challenges/non-divisible-subset/

运动轨迹 练习轨道是关于创建一个程序,该程序将接受一个整数列表和一个数字“k”,并将输出列表中不能被“k”整除且不重复的最大整数数的计数.

我的问题是结果与预期输出不同。 你能检测到我的代码中的任何问题吗?可能这是一个逻辑错误,但我被卡住了。请帮我。

输入 k=9 且输入列表 = 422346306、940894801、696810740、862741861、85835055、313720373, 输出应该是 5 但我的代码得到 6。

public static int nonDivisibleSubset(int k, List<int> s)
    {
        var x = GetPerm(s);


        var y = x.Where(x => x.Value % k != 0).Select(x=>x.Key).ToList();
        var a = y.SelectMany(x => x).ToHashSet();

        return a.Count();

    }

    static Dictionary<List<int>,int> GetPerm (List<int> list)
    {
        Dictionary<List<int>,int> perm = new Dictionary<List<int>, int>();

        for (int i = 0; i < list.Count; i++)
        {
            for (int j = i+1; j < list.Count; j++)
            {
                List<int> sumCouple = new List<int>();
                sumCouple.Add(list[i]);
                sumCouple.Add(list[j]);
                perm.Add(sumCouple, sumCouple.Sum());
            }

        }
        return perm;
    }

【问题讨论】:

  • 问题应包括回答问题所需的所有信息。链接可能会失效。请引用作业的相关部分。
  • Hackerrank 还需要登录,...因此该链接对许多用户来说毫无用处。
  • 添加了运动轨迹

标签: c#


【解决方案1】:

不是整个问题的答案——但你的代码至少有一个问题——List不能用作字典的键,因为它不会覆盖Equals/GetHashCode,所以它将执行参考比较。您可以提供自定义相等比较器:

class PairListEqComparer : IEqualityComparer<List<int>>
{
    public static PairListEqComparer Instance { get; } = new PairListEqComparer();

    public bool Equals(List<int> x, List<int> y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        if (x.Count != 2 || y.Count != 2) return false; // or throw

        return x[0] == y[0] && x[1] == y[1];
    }

    public int GetHashCode(List<int> obj) => HashCode.Combine(obj.Max(), obj.Min(), obj.Count);
}

和用法:

Dictionary<List<int>,int> perm = new Dictionary<List<int>, int>(PairListEqComparer.Instance);

或者考虑使用有序值元组(编译器将生成所需的方法)。

至于解决方案本身 - 有效的蛮力方法是生成所有大小的所有排列,即从 1 到 s.Count 并找到满足条件的最长排列。

【讨论】:

  • 它将执行参考比较,因此导致我的输出不同!该死的,我是 C# 的新手,才学了一年。不管怎么说,还是要谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 2018-08-30
相关资源
最近更新 更多