一个递增数列算法题

jee_asp 2014-04-17 10:16:56
递增数列,如{1,2,3,5,52,110},以大于等于50为增量来检索,
比如上面的数列的检索结果为:
{1,52,110}。
请问有没有好一点的算法?我只知道一个个数进行比较。
...全文
4127 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2014-05-07
  • 打赏
  • 举报
回复
int[] a = { 1, 2, 3, 5, 52, 110 };
List<int> result = new List<int>() { a[0] };
IEnumerable<int> r = a.Skip(1);
while (true)
{
    r = r.SkipWhile(x => x - result[result.Count - 1] < 50);
    if (!r.Any()) break;
    result.Add(r.First());
}
foreach (var item in result)
    Console.WriteLine(item);
佛火 2014-05-07
  • 打赏
  • 举报
回复
引用 6 楼 caozhy 的回复:
你看lz的例子,52-5<50也归为两组。
引用 楼主 jee_asp 的回复:
递增数列,如{1,2,3,5,52,110},以大于等于50为增量来检索, 比如上面的数列的检索结果为: {1,52,110}。 请问有没有好一点的算法?我只知道一个个数进行比较。
楼主的例子是 {1, 52, 110 } 要求大于等于50的增量的。
threenewbee 2014-05-07
  • 打赏
  • 举报
回复
引用 5 楼 gounliey 的回复:
估计没有比循环一次现好的办法

static int[] Find(int[] sortedArray)
{
    if (sortedArray == null || sortedArray.Length == 0)
    {
        return new int[] { };
    }
    var cache = new List<int>(sortedArray.Length);
    int cursor = sortedArray[0];
    cache.Add(cursor);
    for (int i = 1; i < sortedArray.Length; i++)
    {
        if (sortedArray[i] - cursor >= 50)
        {
            cursor = sortedArray[i];
            cache.Add(cursor);
        }
    }
    return cache.ToArray();
}

int[] a = { 1, 2, 3, 5, 52, 110 };
var results = Find(a);
[quote=引用 4 楼 caozhy 的回复:] int[] a = {1,2,3,5,52,110}; int[] result = a.GroupBy(x => x / 50).Select(x => x.First()).ToArray();
版大,你的方式不太可取,如果出现 int[] a = {1,2,3,5,52,, 101, 110}; 你的方法会取到101,而不是110,而101-52 < 50[/quote] 你看lz的例子,52-5<50也归为两组。
佛火 2014-05-07
  • 打赏
  • 举报
回复
估计没有比循环一次现好的办法

static int[] Find(int[] sortedArray)
{
    if (sortedArray == null || sortedArray.Length == 0)
    {
        return new int[] { };
    }
    var cache = new List<int>(sortedArray.Length);
    int cursor = sortedArray[0];
    cache.Add(cursor);
    for (int i = 1; i < sortedArray.Length; i++)
    {
        if (sortedArray[i] - cursor >= 50)
        {
            cursor = sortedArray[i];
            cache.Add(cursor);
        }
    }
    return cache.ToArray();
}

int[] a = { 1, 2, 3, 5, 52, 110 };
var results = Find(a);
引用 4 楼 caozhy 的回复:
int[] a = {1,2,3,5,52,110}; int[] result = a.GroupBy(x => x / 50).Select(x => x.First()).ToArray();
版大,你的方式不太可取,如果出现 int[] a = {1,2,3,5,52,, 101, 110}; 你的方法会取到101,而不是110,而101-52 < 50
threenewbee 2014-05-07
  • 打赏
  • 举报
回复
int[] a = {1,2,3,5,52,110}; int[] result = a.GroupBy(x => x / 50).Select(x => x.First()).ToArray();
宇哥_ 2014-05-07
  • 打赏
  • 举报
回复
用循环判断一个个,就OK了啊
maoyuns 2014-05-07
  • 打赏
  • 举报
回复
循环的话是很快的,不用考虑性能问题,即使你转成list等的自带方法的数列通过组合也能做到
qq775126619 2014-04-17
  • 打赏
  • 举报
回复
递增的话可以考虑循环中取到第一个符合值后以后的值就不用作比较了,循环的话是很快的,不用考虑性能问题,即使你转成list等的自带方法的数列通过组合也能做到,不过他自带的方法里可能还是循环取,跟你一样的。或者说直接通过路径指针去取,我是觉得没必要

17,742

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧