Fastest way to detect duplicate numbers on array vb.net 2005

前端 未结 9 1428
轮回少年
轮回少年 2021-01-20 17:31

I have this project that let user inputs 5 different numbers from 1 to 50. But I want to validate it before saving to DB that i will be 5 unique numbers. What\'s the best an

相关标签:
9条回答
  • 2021-01-20 18:18

    Very late to the party, but what about something like this (C#, sorry)?

    byte[] hits = new byte[51];
    byte[] entries = new byte[] { 1, 12, 12, 32, 26, 49 };
    
    foreach (var entry in entries)
    {
        hits[entry]++;
    }
    

    The elements in the hits array are automatically initialized to 0. When the foreach loop is complete, hits will contain the occurrence count for every number in entries. If any is greater than 1, you have dupes.

    0 讨论(0)
  • 2021-01-20 18:19

    Here's an alternate solution, not sure how it compares, efficiency wise, to the other solutions, but it seems to work (uses LINQ).

    Dim numbers As List<int> = getListOfNumbers()
    Dim allUnique As Boolean = numbers.Distinct().Count() = numbers.Count()
    
    0 讨论(0)
  • 2021-01-20 18:22

    You can use HashSet(Of T) to check this:

    Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
    Dim hash As HashSet(Of Integer) = new HashSet(Of Integer)(numbers)
    
    Dim unique As Boolean = hash.Count = numbers.Count()
    

    This will be much more efficient than options requiring a sort + iteration.

    0 讨论(0)
提交回复
热议问题