LeetCode 初级算法 C# 存在重复

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Testiness_Wind/article/details/82430431

解法一

时间复杂度O(n^2)方法,将数组遍历两次,最容易想到的方法。

        public static bool CheckRepeat1(int[] nums)
        {
            if (nums.Length < 2) return false;

            for (int i = 0; i < nums.Length; i++)
            {
                for (int j = i + 1; j < nums.Length; j++)
                {
                    if (nums[i] == nums[j]) return true;
                }
            }

            return false;
        }

解法二

先对数组进行排序处理,然后检查相邻数据是否存在重复。

        public static bool CheckRepeat2(int[] nums)
        {
            if (nums.Length < 2) return false;

            Array.Sort(nums);

            for (int i = 0; i < nums.Length - 1; i++)
            {
                if (nums[i] == nums[i + 1]) return true;
            }

            return false;
        }

猜你喜欢

转载自blog.csdn.net/Testiness_Wind/article/details/82430431