Skip to content

Instantly share code, notes, and snippets.

@JeffreyZhao
Created November 2, 2012 09:28
Show Gist options
  • Save JeffreyZhao/3999741 to your computer and use it in GitHub Desktop.
Save JeffreyZhao/3999741 to your computer and use it in GitHub Desktop.
// 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.
}
}
}
@yoroto
Copy link

yoroto commented Nov 3, 2012

睡一半想到昨天写错了。。。

    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