Created
November 2, 2012 09:28
-
-
Save JeffreyZhao/3999741 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// As we all know, the generic List<T> class in .NET doesn't | |
// have a RemoveMultiple method. Could you implement it for me? | |
// Say the elements are kept in the _items field, which is an | |
// array of type T. Also, use _count to keep the current number | |
// of elements. | |
// PS: You can compare two items with "==" operator. | |
namespace System.Collections.Generic | |
{ | |
public class List<T> | |
{ | |
private T[] _items; | |
private int _count; | |
public void RemoveMultiple(IEnumerable<T> itemsToRemove) | |
{ | |
// Please implement the method here. | |
} | |
} | |
} |
void Main()
{
var list = new List<int>(new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
var itemsToRemove = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, };
list.Print();
list.RemoveMultiple(itemsToRemove);
list.Print();
}
// Define other methods and classes here
public class List<T>
{
private T[] _items;
private int _count;
public List(IEnumerable<T> values)
{
_items = values.ToArray();
_count = _items.Length;
}
public void Print()
{
Console.WriteLine(string.Join(", ", _items.Take(_count).Select(x => x.ToString())));
}
public void RemoveMultiple(IEnumerable<T> itemsToRemove)
{
// Please implement the method here.
// == 无法通过编译, 这里用了 object.Equals
// 如果查找时间过长,并且可以排序,可以合并算法更快找出所有要删除的索引位置, 此处从略
var indeces = _items.Select((item, index) => new {item, index})
.Where(x => itemsToRemove.Any(y => Equals(y, x.item)))
.Select(x => x.index)
.OrderBy(x => x)
.ToList();
for(var i = 0; i < indeces.Count; i++)
{
var indexStart = indeces[i] - i;
var indexEnd = (i < indeces.Count - 1 ? indeces[i+1] : _count -1) -i;
for(var index = indexStart; index < indexEnd; index++)
{
_items[index] = _items[index+i+1];
}
}
_count = _count - indeces.Count;
}
}
睡一半想到昨天写错了。。。
public void RemoveMultiple(IEnumerable<T> itemsToRemove)
{
foreach (T item in itemsToRemove)
{
for (int i = 0; i < _count; i++)
{
if (_items[i] == item)
{
_items[i] = null;
break;
}
}
}
int p = 0;
int q = 0;
while( p != _count )
{
if (!_items[p] == null)
{
if (p != q)
{
_items[q] = _items[p];
}
q++;
}
p++;
}
for (int i = q; i < _count; i++)
{
_items[i] = null;
}
_count = q;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
void Main()
{
var list = new List(new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
var itemsToRemove = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, };
list.Print();
list.RemoveMultiple(itemsToRemove);
list.Print();
}
// Define other methods and classes here
public class List
{
private T[] _items;
private int _count;