簡體   English   中英

如何檢查我的數組中是否有重復的值?

[英]How do I check if my array has repeated values inside it?

所以這是我的數組。

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

我想做一個搜索循環來檢查是否有重復的值。 我怎么做?

我不想使用任何特殊的內置方法,因為這是一個小數組。

你可以用一個小的 Linq 來做到這一點:

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

Distinct擴展方法刪除任何重復項, Count獲取結果集的大小。 如果它們完全不同,則列表中有一些重復項。

或者,這里有更復雜的查詢,但它可能更有效:

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

GroupBy方法將任何相同的元素組合在一起,如果任何組有多個元素,則Any返回true

上述兩種解決方案都通過使用HashSet<T> ,但您可以像這樣直接使用一個:

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

或者,如果您更喜歡完全不依賴 Linq 的解決方案:

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

看看我的實現,它的genericefficient

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
    }

這里有一些電話

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

用這個:

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;
}

我們必須在第一個循環中從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]);
        }
    }
}

使用 (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];
}

更一般的,10個數字比上面慢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;
}

兩行(慢速重復;)

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

通用擴展方法:

public static bool HasDuplicate<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
    if (source == null)
        throw new ArgumentException(nameof(source));

    HashSet<T> set = new HashSet<T>(comparer);
    foreach (var item in source)
        if (!set.Add(item))
            return true;

    return false;
}

使用散列集添加成員,然后檢查是否存在當前成員的先前出現

public bool ContainsDuplicate(double[] nums) 
{
            int size = nums.Length;
            HashSet<double> set1 = new HashSet<double>();

            for (int i = 0; i < size; i++)
            {
                if (set1.Contains(nums[i]))
                {
                    return true;
                }
                else
                {
                    set1.Add(nums[i]);
                }
            }
            return false;
}
        int[] nums = new int[] { 1, 2, 3, 4, 5};



        Console.WriteLine(AnyDuplicate(nums));
    }
    /// <summary>
    /// Returns true if there is at least a duplicate in the array.
    /// </summary>
    /// <returns></returns>
    static bool AnyDuplicate(int[] numbers)
    {            
        for (int i = 0; i < numbers.Length; i++)
        {
            for (int j = i + 1; j < numbers.Length; j++)
            {
                if (numbers[i] == numbers[j])
                {
                    return true; 
                }
            }
        }
        return false;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM