Contains duplicate

leetcode solution in c#

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1] Output: true Example 2:

Input: nums = [1,2,3,4] Output: false Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true

Constraints:

1 <= nums.length <= 105 -109 <= nums[i] <= 109

Approach 1: comparing each elements of the loop until find the match

using System;

namespace ContainsDuplicate
{
    class Program
    {
        public bool ContainsDuplicate(int[] nums)
        {
            Array.Sort(nums);
            for(int i = 0; i < nums.Length-1; i++)
            {
                for(int j =  i+1; j < nums.Length; j++)
                {
                    if (nums[i] == nums[j])
                    {
                        return true;
                    }
                }

            }

            return false;
        }
        static void Main(string[] args)
        {
            int[] nums = { 3,1,5,2,3 };
            Program obj = new Program();
            Console.WriteLine(obj.ContainsDuplicate(nums));
        }
    }
}

Approach 2: first sort the array then the same element will be next to each other if any concurrent elements is same then it will return true

using System;

namespace ContainsDuplicate
{
    class Program
    {
        public bool ContainsDuplicate(int[] nums)
        {
            Array.Sort(nums);
            for (int i = 1; i < nums.Length; i++)
            {

                if (nums[i] == nums[i - 1])
                {
                    return true;

                }
            }

            return false;
        }
        static void Main(string[] args)
        {
            int[] nums = { 1,2,3,1 };
            Program obj = new Program();
            Console.WriteLine(obj.ContainsDuplicate(nums));
        }
    }
}