如何检查我的数组中是否有重复的值?

时间:2022-01-25 01:49:41

So here is my array.

所以这是我的阵列。

double[] testArray = new double[10];
// will generate a random numbers from 1-20, too lazy to write the code

I want to make a search loop to check if any values are being repeated. How do I do that?

我想创建一个搜索循环来检查是否有重复的值。我怎么做?

I would prefer not to use any special built-in methods since this is a small array.

我宁愿不使用任何特殊的内置方法,因为这是一个小数组。

5 个解决方案

#1


24  

You could do this with a little Linq:

你可以用一点Linq做到这一点:

if (testArray.Length != testArray.Distinct().Count())
{
    Console.WriteLine("Contains duplicates");
}

The Distinct extension method removes any duplicates, and Count gets the size of the result set. If they differ at all, then there are some duplicates in the list.

Distinct扩展方法删除任何重复项,Count获取结果集的大小。如果它们完全不同,那么列表中会有一些重复。

Alternatively, here's more complicated query, but it may be a bit more efficient:

或者,这是更复杂的查询,但它可能更有效:

if (testArray.GroupBy(x => x).Any(g => g.Count() > 1))
{
    Console.WriteLine("Contains duplicates");
}

The GroupBy method will group any identical elements together, and Any return true if any of the groups has more than one element.

GroupBy方法将任何相同的元素组合在一起,如果任何组具有多个元素,则Any返回true。

Both of the above solutions work by utilizing a HashSet<T>, but you can use one directly like this:

上述两种解决方案都可以通过使用HashSet 来工作,但您可以直接使用它:

if (!testArray.All(new HashSet<double>().Add))
{
    Console.WriteLine("Contains duplicates");
}

Or if you prefer a solution that doesn't rely on Linq at all:

或者,如果您更喜欢完全不依赖于Linq的解决方案:

var hashSet = new HashSet<double>();
foreach(var x in testArray) 
{
    if (!hashSet.Add(x)) 
    {
        Console.WriteLine("Contains duplicates");
        break;
    }
}

#2


1  

Use this:

bool CheckUniqueness(double[] values)
{
    var uniqueValues = new HashSet<double>();
    foreach (double d in values)
    {
        if(uniqueValues.Contains(d))
        {
            return false;
        }
        uniqueValues.Add(d);
    }
    return true;
}

#3


1  

take look at my implementation its generic and efficient

看看我的实现它的通用性和高效性

public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> map = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i++)
        {
            if (map.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            map.Add(items[i], true);
        }
        return false; // no duplicates
    }

here are some calls

这里有一些电话

string[] strings = new[] { "1", "2", "3" };
Utility.HasDuplicates(strings)// this will return false

int[] items=new []{1,2,3,1};
Utility.HasDuplicates(items)// this will return true

#4


0  

With (OP) 10 random doubles quite fast. The chance of a repeat: ~0.000002 %.

随着(OP)10个随机双打相当快。重复的几率:~0.000002%。

static bool repeat(double[] a)
{
    return
        a[0] == a[1] || a[0] == a[2] || a[0] == a[3] || a[0] == a[4] ||
        a[0] == a[5] || a[0] == a[6] || a[0] == a[7] || a[0] == a[8] ||
        a[0] == a[9] || a[1] == a[2] || a[1] == a[3] || a[1] == a[4] ||
        a[1] == a[5] || a[1] == a[6] || a[1] == a[7] || a[1] == a[8] ||
        a[1] == a[9] || a[2] == a[3] || a[2] == a[4] || a[2] == a[5] ||
        a[2] == a[6] || a[2] == a[7] || a[2] == a[8] || a[2] == a[9] ||
        a[3] == a[4] || a[3] == a[5] || a[3] == a[6] || a[3] == a[7] ||
        a[3] == a[8] || a[3] == a[9] || a[4] == a[5] || a[4] == a[6] ||
        a[4] == a[7] || a[4] == a[8] || a[4] == a[9] || a[5] == a[6] ||
        a[5] == a[7] || a[5] == a[8] || a[5] == a[9] || a[6] == a[7] ||
        a[6] == a[8] || a[6] == a[9] || a[7] == a[8] || a[7] == a[9] ||
        a[8] == a[9];
}

More general, with 10 numbers ~2 times slower than above,
but ~7 times faster than the hashset approach.

更一般地说,10个数字比上面慢2~2倍,但比hashset方法快〜7倍。

static bool repeat(double[] a)
{
    int k = a.Length - 1;
    if (k < 70)
    {
        double aj;
        for (int i = 0, j; i < k; )
        {
            for (aj = a[k--], j = k; j >= i; j--)
                if (aj == a[j]) return true;
            for (aj = a[i++], j = i; j <= k; j++)
                if (aj == a[j]) return true;
        }
        return false;
    }
    var h = new HashSet<double>();
    while (k >= 0) if (!h.Add(a[k--])) return false;
    return true;
}

Two lines (slow with a repeat ;)

两行(缓慢重复;)

static bool repeat(double[] a)
{ return (new HashSet<double>(a).Count < a.Length); }

#5


0  

We must initialize j from i on the first loop and add one(i+1) because we want to compare first loop value with the next value of same array.

我们必须在第一个循环中从i初始化j并添加一个(i + 1),因为我们想要将第一个循环值与同一个数组的下一个值进行比较。

int[] arr = new int[]{1,2,3,1,4,2,5,4};

//create one loop for arr values
for (int i = 0;  i < arr.Length; i++)
{
    //create nested loop for compare current values with actual value of arr
    for (int j = i+1; j < arr.Length; j++)
    {

        //and here we put our condition
        if (arr[i] == arr[j])
        {
            Console.WriteLine(arr[i]);
        }
    }
}

#1


24  

You could do this with a little Linq:

你可以用一点Linq做到这一点:

if (testArray.Length != testArray.Distinct().Count())
{
    Console.WriteLine("Contains duplicates");
}

The Distinct extension method removes any duplicates, and Count gets the size of the result set. If they differ at all, then there are some duplicates in the list.

Distinct扩展方法删除任何重复项,Count获取结果集的大小。如果它们完全不同,那么列表中会有一些重复。

Alternatively, here's more complicated query, but it may be a bit more efficient:

或者,这是更复杂的查询,但它可能更有效:

if (testArray.GroupBy(x => x).Any(g => g.Count() > 1))
{
    Console.WriteLine("Contains duplicates");
}

The GroupBy method will group any identical elements together, and Any return true if any of the groups has more than one element.

GroupBy方法将任何相同的元素组合在一起,如果任何组具有多个元素,则Any返回true。

Both of the above solutions work by utilizing a HashSet<T>, but you can use one directly like this:

上述两种解决方案都可以通过使用HashSet 来工作,但您可以直接使用它:

if (!testArray.All(new HashSet<double>().Add))
{
    Console.WriteLine("Contains duplicates");
}

Or if you prefer a solution that doesn't rely on Linq at all:

或者,如果您更喜欢完全不依赖于Linq的解决方案:

var hashSet = new HashSet<double>();
foreach(var x in testArray) 
{
    if (!hashSet.Add(x)) 
    {
        Console.WriteLine("Contains duplicates");
        break;
    }
}

#2


1  

Use this:

bool CheckUniqueness(double[] values)
{
    var uniqueValues = new HashSet<double>();
    foreach (double d in values)
    {
        if(uniqueValues.Contains(d))
        {
            return false;
        }
        uniqueValues.Add(d);
    }
    return true;
}

#3


1  

take look at my implementation its generic and efficient

看看我的实现它的通用性和高效性

public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> map = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i++)
        {
            if (map.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            map.Add(items[i], true);
        }
        return false; // no duplicates
    }

here are some calls

这里有一些电话

string[] strings = new[] { "1", "2", "3" };
Utility.HasDuplicates(strings)// this will return false

int[] items=new []{1,2,3,1};
Utility.HasDuplicates(items)// this will return true

#4


0  

With (OP) 10 random doubles quite fast. The chance of a repeat: ~0.000002 %.

随着(OP)10个随机双打相当快。重复的几率:~0.000002%。

static bool repeat(double[] a)
{
    return
        a[0] == a[1] || a[0] == a[2] || a[0] == a[3] || a[0] == a[4] ||
        a[0] == a[5] || a[0] == a[6] || a[0] == a[7] || a[0] == a[8] ||
        a[0] == a[9] || a[1] == a[2] || a[1] == a[3] || a[1] == a[4] ||
        a[1] == a[5] || a[1] == a[6] || a[1] == a[7] || a[1] == a[8] ||
        a[1] == a[9] || a[2] == a[3] || a[2] == a[4] || a[2] == a[5] ||
        a[2] == a[6] || a[2] == a[7] || a[2] == a[8] || a[2] == a[9] ||
        a[3] == a[4] || a[3] == a[5] || a[3] == a[6] || a[3] == a[7] ||
        a[3] == a[8] || a[3] == a[9] || a[4] == a[5] || a[4] == a[6] ||
        a[4] == a[7] || a[4] == a[8] || a[4] == a[9] || a[5] == a[6] ||
        a[5] == a[7] || a[5] == a[8] || a[5] == a[9] || a[6] == a[7] ||
        a[6] == a[8] || a[6] == a[9] || a[7] == a[8] || a[7] == a[9] ||
        a[8] == a[9];
}

More general, with 10 numbers ~2 times slower than above,
but ~7 times faster than the hashset approach.

更一般地说,10个数字比上面慢2~2倍,但比hashset方法快〜7倍。

static bool repeat(double[] a)
{
    int k = a.Length - 1;
    if (k < 70)
    {
        double aj;
        for (int i = 0, j; i < k; )
        {
            for (aj = a[k--], j = k; j >= i; j--)
                if (aj == a[j]) return true;
            for (aj = a[i++], j = i; j <= k; j++)
                if (aj == a[j]) return true;
        }
        return false;
    }
    var h = new HashSet<double>();
    while (k >= 0) if (!h.Add(a[k--])) return false;
    return true;
}

Two lines (slow with a repeat ;)

两行(缓慢重复;)

static bool repeat(double[] a)
{ return (new HashSet<double>(a).Count < a.Length); }

#5


0  

We must initialize j from i on the first loop and add one(i+1) because we want to compare first loop value with the next value of same array.

我们必须在第一个循环中从i初始化j并添加一个(i + 1),因为我们想要将第一个循环值与同一个数组的下一个值进行比较。

int[] arr = new int[]{1,2,3,1,4,2,5,4};

//create one loop for arr values
for (int i = 0;  i < arr.Length; i++)
{
    //create nested loop for compare current values with actual value of arr
    for (int j = i+1; j < arr.Length; j++)
    {

        //and here we put our condition
        if (arr[i] == arr[j])
        {
            Console.WriteLine(arr[i]);
        }
    }
}