C#实现检查数组中是否存在相同元素

1.代码(主函数)

static void Main(string[] args)
        {
            int[] a = { 1, 2, 3,3 };
            bool b = Check(a);
            Console.WriteLine(b);
        }
        private static bool Check(int[]Input)
        {
            //bool have=true;
            for(int i = 0; i< Input.Length;i++)
            {
                //int a = Input[i];
                for (int j = i+1;j<Input.Length;j++)
                {
                    //int b = Input[j];
                    if (Input[i] == Input[j]) 
                        return true;
                    
                }
            }
            
            return false;

        }

2.运行结果

 

设置数组a的值是{1,2,3,3}结果返回true,数组有重复值

 

设置数组a的值是{1,2,3,4}结果返回false,数组无重复值

3.原理

    遍历两遍数据,第一次取出数据第二次将数据与后面的数进行逐个比较,若有相同的返回结果true,若无,则返回false


版权声明:本文为qq_59081708原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。