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