s1.5 力扣之存在重复元素

我们可以先对数组进行排序,然后再比较。因为排序之后如果有相同的,那么相同的值肯定是挨着的,我们只需要在排序之后两两比较即可

static void Main(string[] args)
        {
            int[] nums = { 1, 1, 2,6,5,2,1 };
            var flag = containsDuplicate(nums);
        } 

static bool containsDuplicate(int[] nums)
        {
            Array.Sort(nums);
            for (int ind = 1; ind < nums.Length; ind++)
            {
                if (nums[ind] == nums[ind - 1])
                {
                    return true;
                }
            }
            return false;
        }
原文地址:https://www.cnblogs.com/yzenet/p/15718604.html