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

前端 未结 8 1391
悲哀的现实
悲哀的现实 2020-12-01 20:55

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

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 21:12

    use a hashset to add members to, then check if there a previous occurrence of current member

    public bool ContainsDuplicate(double[] nums) 
    {
                int size = nums.Length;
                HashSet set1 = new HashSet();
    
                for (int i = 0; i < size; i++)
                {
                    if (set1.Contains(nums[i]))
                    {
                        return true;
                    }
                    else
                    {
                        set1.Add(nums[i]);
                    }
                }
                return false;
    }
    

提交回复
热议问题