描述:
爱丽丝跟鲍勃去旅游,拍了很多照片回来,叫查理过来一起看照片。但是查理并不是很乐意,因为照片中有太多张重复了,他可不想看40多次埃菲尔铁塔。他对他们说,等你们把重复的照片删掉,最多保留N张,我再过来看。假设照片是一个整数数组,能否帮他们把数组中重复的数字删掉,最多保留N个呢?
例如:
Kata.DeleteNth (new int[] {20,37,20,21}, 1) // 返回 [20,37,21]
Kata.DeleteNth (new int[] {1,1,3,3,7,2,2,2,2}, 3) // 返回 [1, 1, 3, 3, 7, 2, 2, 2]
MyCode:
using System;
using System.Collections.Generic;
using System.Linq;
public class Kata {
public static int[] DeleteNth(int[] arr, int x)
{
var result = new List<int>();//实例化一个List<int>对象result
foreach(var item in arr) //遍历数组,把相等数值小于x的数赋给result
{
if(result.Count(i => i == item) < x)
result.Add(item);
}
return result.ToArray();
}
}
CodeWar:
using System;
using System.Collections.Generic;
using System.Linq;
public class Kata {
public static int[] DeleteNth(int[] arr, int x) {
return arr.Where((t,i)=>arr.Take(i+1).Count(s=>s==t) <= x).ToArray();
}
}

513

被折叠的 条评论
为什么被折叠?



