Data structure: insert, remove, contains, get random element, all at O(1)

后端 未结 14 733
别跟我提以往
别跟我提以往 2020-11-29 14:53

I was given this problem in an interview. How would you have answered?

Design a data structure that offers the following operations in O(1) time:

  • inse
14条回答
  •  我在风中等你
    2020-11-29 15:05

    Here is a C# solution to that problem I came up with a little while back when asked the same question. It implements Add, Remove, Contains, and Random along with other standard .NET interfaces. Not that you would ever need to implement it in such detail during an interview but it's nice to have a concrete solution to look at...

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    
    /// 
    /// This class represents an unordered bag of items with the
    /// the capability to get a random item.  All operations are O(1).
    /// 
    /// The type of the item.
    public class Bag : ICollection, IEnumerable, ICollection, IEnumerable
    {
        private Dictionary index;
        private List items;
        private Random rand;
        private object syncRoot;
    
        /// 
        /// Initializes a new instance of the  class.
        /// 
        public Bag()
            : this(0)
        {
        }
    
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The capacity.
        public Bag(int capacity)
        {
            this.index = new Dictionary(capacity);
            this.items = new List(capacity);
        }
    
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The collection.
        public Bag(IEnumerable collection)
        {
            this.items = new List(collection);
            this.index = this.items
                .Select((value, index) => new { value, index })
                .ToDictionary(pair => pair.value, pair => pair.index);
        }
    
        /// 
        /// Get random item from bag.
        /// 
        /// Random item from bag.
        /// 
        /// The bag is empty.
        /// 
        public T Random()
        {
            if (this.items.Count == 0)
            {
                throw new InvalidOperationException();
            }
    
            if (this.rand == null)
            {
                this.rand = new Random();
            }
    
            int randomIndex = this.rand.Next(0, this.items.Count);
            return this.items[randomIndex];
        }
    
        /// 
        /// Adds the specified item.
        /// 
        /// The item.
        public void Add(T item)
        {
            this.index.Add(item, this.items.Count);
            this.items.Add(item);
        }
    
        /// 
        /// Removes the specified item.
        /// 
        /// The item.
        /// 
        public bool Remove(T item)
        {
            // Replace index of value to remove with last item in values list
            int keyIndex = this.index[item];
            T lastItem = this.items[this.items.Count - 1];
            this.items[keyIndex] = lastItem;
    
            // Update index in dictionary for last item that was just moved
            this.index[lastItem] = keyIndex;
    
            // Remove old value
            this.index.Remove(item);
            this.items.RemoveAt(this.items.Count - 1);
    
            return true;
        }
    
        /// 
        public bool Contains(T item)
        {
            return this.index.ContainsKey(item);
        }
    
        /// 
        public void Clear()
        {
            this.index.Clear();
            this.items.Clear();
        }
    
        /// 
        public int Count
        {
            get { return this.items.Count; }
        }
    
        /// 
        public void CopyTo(T[] array, int arrayIndex)
        {
            this.items.CopyTo(array, arrayIndex);
        }
    
        /// 
        public bool IsReadOnly
        {
            get { return false; }
        }
    
        /// 
        public IEnumerator GetEnumerator()
        {
            foreach (var value in this.items)
            {
                yield return value;
            }
        }
    
        /// 
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    
        /// 
        public void CopyTo(Array array, int index)
        {
            this.CopyTo(array as T[], index);
        }
    
        /// 
        public bool IsSynchronized
        {
            get { return false; }
        }
    
        /// 
        public object SyncRoot
        {
            get
            {
                if (this.syncRoot == null)
                {
                    Interlocked.CompareExchange(
                        ref this.syncRoot,
                        new object(),
                        null);
                }
    
                return this.syncRoot;
    
            }
        }
    }
    
        

    提交回复
    热议问题