有100万个数字(1到9),其中只有1个数字重复2次,如何快速找出该数字

本文介绍了一种使用C#来找出100万个数字中唯一重复数字的方法。通过遍历并计数每个数字出现的次数,最终定位到那个重复了两次的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有100万个数字(1到9),其中只有1个数字重复2次,如何快速找出该数字

 

rt, C# codes as below:

using System;

using System.Collections.Generic;

 

namespace ConsoleApp

{

    class Program

    {

        static void Main(string[] args)

        {

            List<int> list = new List<int>();

 

            for (int i = 1; i < 10; i++)

            {

                for (int j = 0; j < i; j++)

                {

                    list.Add(i);

                }

 

                list.Add(1);

                list.Add(1);

            }

 

            Console.WriteLine(GetNum(list));

            Console.ReadKey();

        }

 

        static int GetNum(List<int> listNums)

        {

            bool[] ifRemoved = new bool[9];

            int[] counterTimes = new int[9];

 

            int movedNum = 0;

 

            foreach (int i in listNums)

            {

                if (i <= 0 || i > 9)

                    throw new System.FormatException(string.Format("Unexpected num value {0}!", i));

 

                if (ifRemoved[i - 1] == false)

                {

                    counterTimes[i - 1]++;

 

                    if (counterTimes[i - 1] > 2)

                    {

                        ifRemoved[i - 1] = true;

                        movedNum++;

                        if (movedNum == 8)

                        {

                            for (int j = 0; j < 9; j++)

                            {

                                if (ifRemoved[j] == false)

                                    return j + 1;

                            }

                        }

                    }

                }

 

            }

 

            for (int j = 0; j < 9; j++)

            {

                if (counterTimes[j] == 2)

                    return j + 1;

            }

 

            throw new System.ArgumentException("There is no suitable num in the param array!");

        }

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值