日期:2014-05-18  浏览次数:20817 次

这道泛型题,如何计算?
List<int> num = new List<int> { 7, 0, 1, 2, 3, 4, 5, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 0, 1, 0, 1, 2, 3, 4, 5, 6 };


如何:

1.返回最后一个0前面的数值,答案是:1
2.返回倒数第二个0前面的数值;答案是:2



------解决方案--------------------
C# code

 List<int> a = new List<int>();//记录为0的项的编号
            List<int> num = new List<int> { 7, 0, 1, 2, 3, 4, 5, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 0, 1, 0, 1, 2, 3, 4, 5, 6 };

            for (int i = 0; i < num.Count; i++)
            {
                if (num[i] == 0)
                {
                    a.Add(i);
                }
            }
            Console.WriteLine(num[a[a.Count-1]-1].ToString());
            Console.WriteLine(num[a[a.Count - 2]-1].ToString());
            Console.ReadLine();

------解决方案--------------------
C# code
List<int> num = new List<int> { 7, 0, 1, 2, 3, 4, 5, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 0, 1, 0, 1, 2, 3, 4, 5, 6 };
var query = (from v in num.Select((x, i) => new { x, i })
            let idx = num.Select((x, i) => new { x, i }).Where(y => y.x == 0 && y.i < v.i).LastOrDefault() ?? new { x = 0, i = 0 }
            group v by idx.i into g
            orderby g.Key descending
            select new { Key = g.Key, items = g.Take(g.Count() - 1) }).ToList();
int x1 = query[1].items.Last().x;
int x2 = query[2].items.Last().x;
Console.WriteLine(x1 + ", " + x2);

------解决方案--------------------
C# code

List<int> num = new List<int> { 7, 0, 1, 2, 3, 4, 5, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 0, 1, 0, 1, 2, 3, 4, 5, 6 };
var aa = string.Join("", num.ToArray()).Split('0');
var num1 = aa[aa.Length - 2].Last().ToString(); //倒数第1个0前面的数
var num2 = aa[aa.Length - 3].Last().ToString(); //倒数第2个0前面的数