当前位置: 代码迷 >> .NET Framework >> 一个递加数列算法题
  详细解决方案

一个递加数列算法题

热度:73   发布时间:2016-05-01 23:32:48.0
一个递增数列算法题
递增数列,如{1,2,3,5,52,110},以大于等于50为增量来检索,
比如上面的数列的检索结果为:
{1,52,110}。
请问有没有好一点的算法?我只知道一个个数进行比较。
------解决方案--------------------
int[] a = {1,2,3,5,52,110};
int[] result = a.GroupBy(x => x / 50).Select(x => x.First()).ToArray();
------解决方案--------------------
估计没有比循环一次现好的办法


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);


引用:
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
  相关解决方案