C# 数组去重


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();
return arr.Where((t,i)=>arr.Take(i+1).Count(s=>s==t) <= x).ToArray();
}

 

example:

Kata.DeleteNth (new int[] {20,37,20,21}, 1) // return [20,37,21]

Kata.DeleteNth (new int[] {1,1,3,3,7,2,2,2,2}, 3) // return [1, 1, 3, 3, 7, 2, 2, 2]

 

[Test]
public void TestSimple2()
{
var expected = new int[] {1, 1, 3, 3, 7, 2, 2, 2};

var actual = Kata.DeleteNth(new int[] {1,1,3,3,7,2,2,2,2}, 3);

CollectionAssert.AreEqual(expected, actual);
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM