一个数组,下标从0到n,元素为从0到n的整数。判断其中是否有重复元素

本文介绍了一个简单的算法,用于检测输入数组中是否存在重复数值。通过双重循环遍历数组,并利用一个特殊设计的函数来判断是否有重复元素。该方法适用于小规模数据集。

手动调一下,只是判断有无重复的话, 可用一个两重循环搞定:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DupProject
{
    class Program
    {
        static void Main(string[] args)
        {
            const int n = 5;
            int[] a = new int[n];


            for (int i = 0; i < n; i++)
            {
                Console.WriteLine("Please input the array, number from {0}-{1}",0, n-1);
                a[i] = Convert.ToInt32(Console.ReadLine());


            }

            bool t = hasDup(a,n);
            if (t)
            {

                Console.WriteLine("Found dup value");

            }

            else
                Console.WriteLine("No dup value");

 

        }

        static bool hasDup(int[] a, int n)
        {
               
                for (int i = 0; i < n; i++)
                {
                    while (a[i] != i)
                    {

                        int t = a[a[i]];
                        if (t != a[i])
                        {
                            a[a[i]] = a[i];
                            a[i] = t;
                        }
                        else
                        {
                            a[i] = -1;
                            return true;

                        }

 

                    }
                }
               

               return false ;
            }
           
       
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值