如何在数组中查找重复的相邻对

本文关键字:查找 数组 | 更新日期: 2023-09-27 17:49:53

我想写一个简单易行的方法,让我能够在数组中找到一对重复项,并显示该对存在的索引号。

到目前为止,我只有方法头和一个输出的例子

int Duplicates (int[] testArray){
int[] testArray = {1,5,6,8,9,4,4,6,3,2};
}

我唯一想返回的是相邻对的索引位置,即在这种情况下为5,即(4,4(。如果没有相邻的配对,我也希望能够打印"没有找到重复的配对">

有人能帮我开始吗,因为我甚至不知道一个人会如何开始做这样的事情。

如何在数组中查找重复的相邻对

尝试以下Linq查询演示

int[] testArray = {1,5,6,8,9,4,4,6,3,2};
var adjacentDuplicate = testArray
    .Skip(1)
    .Where((value,index) => value == testArray[index])
    .Distinct();
if (adjacentDuplicate.Any() )
{    
    // Print adjacentDuplicate
}
else
{
   // No duplicates found.
}

编辑

以下是针对重复项索引的LINQ查询。

var adjacentIndex = testArray
    .Skip(1)
    .Select((value,index) => value == testArray[index] ? index : -1)
    .Where (x=> x!= -1);

在这个LINQ查询中,我能想到的唯一缺点是它使用-1作为丢弃值。在索引的情况下,它总是true,但我通常不建议这样做。它所做的是检查数组的下一个元素是否与当前元素相同,如果为true,则返回当前索引,否则返回-1,然后只选择大于零的索引。

int[] testArray = {1, 5, 6, 8, 9, 4, 4, 6, 3, 2, 2};
var duplicateIndexes = testArray.
            Select((value, index) => testArray.Length > index + 1 &&
                                     testArray[index + 1] == value ? index : -1).
            Where(index => index > 0).
            ToArray();

分解问题时非常简单,您必须查看每个元素,然后将其与下一个元素进行比较。唯一的主要问题是,如果你将最后一个元素的索引与索引+1进行比较,你将用完数组,这将导致数组越界异常,这就是为什么我们检查我们的位置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Misc
{
    class Program
    {
        static int duplicates(int[] array)
        {
            for (int i = 0; i < array.Length-1; i++)
            {
                if (array[i] == array[i+1])
                {
                    return i;
                }
            }
            return -1;
        }
        static void Main(string[] args)
        {
            int[] testArray = { 1, 5, 6, 8, 9, 4, 4, 6, 3, 2 };
            Console.WriteLine(duplicates(testArray));
            Console.ReadKey(); // block 
        }
    }
}
int previousValue = -1; //set it to something you're not expecting
for (int i=0; i <testArray.Count; i++) {
    int currentValue = testArray[i];
    if (currentValue.equals(previousValue) {
      //we have a duplicate
       duplicateList.add(i); //for the position of the duplicate
    }
    previousValue = currentValue;
}
if (duplicateList.Count == 0) {
   //no duplicates found
} else {
   return duplicateList.toArray();
}

解释-我们将通过一次一个的方式来完成这一过程。

for循环每次都会将值i递增一,直到它遍历整个数组。

在每个步骤中,当前值将与以前的值进行核对。如果它们相同,则该位置将添加到输出中。然后,上一个值变成最后一个当前值,循环继续。