Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Ninputer
Forked from JeffreyZhao/List.cs
Created November 2, 2012 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ninputer/4000340 to your computer and use it in GitHub Desktop.
Save Ninputer/4000340 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)
{
int setIndex = 0;
Dictionary<T, int> items = new Dictionary<T, int>();
foreach (var item in itemsToRemove)
{
if (items.ContainsKey(item))
{
items[item]++;
}
else
{
items[item] = 1;
}
}
for (int getIndex = 0; getIndex < _count; getIndex++)
{
T current = _items[getIndex];
if (items.ContainsKey(current))
{
items[current]--;
if (items[current] == 0)
{
items.Remove(current);
}
continue;
}
_items[setIndex++] = _items[getIndex];
}
for (int i = setIndex; i < _count; i++)
{
_items[i] = default(T);
}
_count = setIndex;
}
}
}
@walterhuangsz
Copy link

Hi Jeffrey, would you review my answer please?
I use dictionary to save and remove the objects, since dictionary is easy to find out a key/value pair, and we need to create it once.

public class List
{
private T[] _items;
private int _count;

    public void RemoveMultiple(IEnumerable<T> itemsToRemove)
    {
        Dictionary<T, int> dic = new Dictionary<T, int>();

        _count = _items.Length;
        for (int i = 0; i < _items.Length; i++)
        {
            dic.Add(_items[i], i);
        }

        foreach (T item in itemsToRemove)
        {
            if (dic.ContainsKey(item))
            {
                dic.Remove(item);
                _count--;
                if (_count == 0)
                {
                    break;
                }
            }
        }

        if (_count > 0)
        {
            _items = new T[_count];
            foreach (T key in dic.Keys)
            {
                _count--;
                _items[_count] = key;
            }
        }
        else
        {
            _items = null;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment