列表的嵌套哈希集?

时间:2013-04-09 00:59:56

标签: c# list nested hashset

我正在处理其中一个项目Euler问题,我想采用创建值列表的方法,并将列表添加到Hashset,这样我就可以在列表已经存在的情况下以恒定时间进行评估在hashset中,最终目标是计算我的最终结果的hashset中的列表数。

我遇到的问题是以这种方式创建列表。

HashSet<List<int>> finalList = new HashSet<List<int>>();
List<int> candidate = new List<int>();
candidate.Add(5);
finalList.Add(candidate);

if (finalList.Contains(candidate) == false) finalList.Add(candidate);
candidate.Clear();

//try next value

显然,当我清除候选人并且没有给我想要的结果时,finalList[0]项目被清除。是否有可能像这样的列表(整数)的哈希集?我如何确保每次实例化一个新列表并将其作为新项添加到hashset中,或许可以说在for循环中测试了许多值和可能的列表组合?

3 个答案:

答案 0 :(得分:1)

为什么不使用每个列表唯一的值作为键或标识符?您可以为您的密钥创建一个HashSet,用于解锁您的列表。

答案 1 :(得分:0)

您可以改用词典。唯一的事情是你必须测试以查看字典是否已经有列表。通过创建一个支持这种需求的简单类,这很容易做到。

class TheSimpleListManager
{
    private Dictionary<String, List<Int32>> Lists = new Dictionary<String, List<Int32>>();

    public void AddList(String key, List<Int32> list)
    {
       if(!Lists.ContainsKey(key))
       {
           Lists.Add(key, list);
       }
       else
       {
          // list already exists....
       }
    }
}

这只是一种方法的快速示例。

答案 2 :(得分:0)

修复您的clear问题:由于它是对象引用,您必须创建new List并将其添加到HashSet。 您可以通过将旧List传递给其构造函数来创建新List。

        HashSet<List<int>> finalList = new HashSet<List<int>>();
        List<int> candidate = new List<int>();

        candidate.Add(5);

        var newList = new List<int>(candidate);
        finalList.Add(newList);

        if (finalList.Contains(newList) == false) //Not required for HashSet
            finalList.Add(newList);

        candidate.Clear();

注意 HashSet在添加项目之前在内部执行contains。换句话说,即使您执行finalList.Add(newList); n次,也只会添加newList一次。因此,没有必要进行包含检查。