Smallest unused ID

本文介绍了一种高效的方法来查找已使用ID集合中的最小未使用ID。通过对比两种实现方式:一种是通过排序和遍历数组,另一种是利用Linq的Except方法。后者更为简洁且在某些场景下更高效。

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

http://www.codewars.com/kata/smallest-unused-id

Description:

Hey awesome programmer!

You've got much data to manage and of course you use zero-based and non-negative ID's to make each data item unique!

Therefore you need a method, which returns the smallest unused ID for your next new data item...

Go on and code some pure awesomeness!

 

自己写了一段超级烂的

  Console.WriteLine("Length = {0}", ids.Length);
            ids = ids.OrderBy(x => x).ToArray();
            foreach (var number in ids)
            {
                Console.Write("{0} ", number);
            }
            Console.WriteLine();

            int count = ids.Count();
            int result = ids.Min() - 1;
            if (result != -1)
            {
                return 0;
            }
            bool loopAllNumber = true;
            for (int i = 0; i < count; i++)
            {
                result++;
                if (result != ids[i])
                {
                    loopAllNumber = false;
                    break;
                }
            }
            Console.WriteLine("after for loop,result = {0}", result);
            if (loopAllNumber)
            {
                result++;
            }
            return result;

 

其他人写的,使用了Linq的Except

   var max=ids.Max();
   var excepts= Enumerable.Range(0, max).Except(ids);
           return excepts.Count() == 0 ? max + 1 : excepts.Min();

 

//
// 摘要:
// 通过使用默认的相等比较器对值进行比较生成两个序列的差集。
//
// 参数:
// first:
// 一个 System.Collections.Generic.IEnumerable<T>,将返回其不在 second 中的元素。
//
// second:
// 一个 System.Collections.Generic.IEnumerable<T>,如果它的元素也出现在第一个序列中,则将导致从返回的序列中移除这些元素。
//
// 类型参数:
// TSource:
// 输入序列中的元素的类型。
//
// 返回结果:
// 包含两个序列元素的差集的序列。
//
// 异常:
// System.ArgumentNullException:
// first 或 second 为 null。
public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值