查找多个数组中所有匹配元素的索引

时间:2018-11-21 18:52:08

标签: c# arrays

假设我有以下两个数组

int[] first = { 1, 2, 3, 4, 5, 6, 12, 13, 14 };
int[] second = { 12, 13, 14, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };

我想要的结果如下:

matching index from the first = 6,7,8 
matching index from second = 0,1,2 

条件:我无法对数组进行排序以找到索引,并且数组可以有任意数量。

我正在寻找一些有效的解决方案,我将很高兴为您提供帮助。 预先感谢。

下面是我为两个数组编写的代码:

class Program
{
    static void Main(string[] args)
    {
        int[] first = { 1, 2, 3, 4, 5, 6, 12, 13, 14 };
        int[] second = { 12, 13, 14, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
        IndexArray sameIndexArray = CompareArray(first, second);
        Console.WriteLine("FOLLOWING ARE THE INDEX WITH SAME VALUE FOR FIRST ARRAY");
        foreach (var index in sameIndexArray.FirstArray)
        {
            Console.WriteLine(index);
        }
        Console.WriteLine("FOLLOWING ARE THE INDEX WITH SAME VALUE FOR SECOND ARRAY");
        foreach (var index in sameIndexArray.SecondArray)
        {
            Console.WriteLine(index);
        }

        Console.ReadKey();
    }

    private static IndexArray CompareArray(int[] firstArray, int[] secondArray)
    {
        IndexArray arrayIndex = new IndexArray();
        arrayIndex.FirstArray = new List<int>();
        arrayIndex.SecondArray = new List<int>();
        for (int i = 0; i < firstArray.Length; i++)
        {
            for (int j = 0; j < secondArray.Length; j++)
            {
                if (firstArray[i] == secondArray[j])
                {
                    arrayIndex.FirstArray.Add(i);
                    arrayIndex.SecondArray.Add(j);
                }
            }
        }

        return arrayIndex;
    }
}

public class IndexArray
{
    public List<int> FirstArray { get; set; }
    public List<int> SecondArray { get; set; }
}

2 个答案:

答案 0 :(得分:3)

您的解是O(N ^ 2)。 O(N)或O(N log N)解决方案应该可行:

  • 为每个集合创建一个HashSet
  • 对第一组进行迭代,并按hashset2进行过滤。包含并打印索引
  • 反之亦然

类似这样的东西:

private static IndexArray CompareArray(int[] firstArray, int[] secondArray)
{
    IndexArray arrayIndex = new IndexArray();
    var hashset2 = new HashSet<int>(secondArray);
    for (int i = 0; i < firstArray.Length; i++)
    {
        if (hashset2.Contains(firstArray[i]))
            arrayIndex.FirstArray.Add(i);
    }
    var hashset1 = new HashSet<int>(firstArray);
    for (int i = 0; i < secondArray.Length; i++)
    {
        if (hashset1.Contains(secondArray[i]))
            arrayIndex.SecondArray.Add(i);
    }

    return arrayIndex;
}

答案 1 :(得分:0)

如果这是有效的代码,则可能更适合代码审查。

我会放弃

arrayIndex.FirstArray = new List<int>();
arrayIndex.SecondArray = new List<int>();

添加

public List<int> FirstArray  { get; } = new List<int>();
public List<int> SecondArray { get; } = new List<int>();

Arraylookup很快,但我会添加

int first = firstArray[i];

然后使用它。

WritelLine将写一行。

相关问题