Skip to content

Instantly share code, notes, and snippets.

@liuguiyangnwpu
Last active August 4, 2016 04:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuguiyangnwpu/5a1f8c4543931e614a0acba75ef214df to your computer and use it in GitHub Desktop.
Save liuguiyangnwpu/5a1f8c4543931e614a0acba75ef214df to your computer and use it in GitHub Desktop.
在数据结构设计中的重要思路,替换原则
  • 对于一个单链表,我们假设这样一种情况,我们不知道单链表的头节点,我们只是知道单链表中某一个节点的指针,现在我们想删除这个节点,我们如何做到?

    • 第一个方案,我们假设一个Flag,确定当我们访问链表中的数据为Flag标志信息的时候,我们可以认为这个节点是我们已经被标志的删除节点;
    • 第二个方案(替换原则),我们可以将该节点的后继节点的信息拷贝到当前的节点上,然后将当前的节点的后继节点删除即可;
  • 在我做leetcode是遇到这样的一个问题,设计一个数据结构,实现插入、删除、随机获取一个数据的均需要咋O(1)的时间完成。

class RandomizedSet {
public:
    /** Initialize your data structure here. */
    RandomizedSet() {
        
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if(hashtable.count(val) == 0) {
            data.push_back(val);
            hashtable[val] = data.size()-1;
            return true;
        }
        return false;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if(hashtable.count(val) != 0) {
            int index = hashtable[val];
            data[index] = data[data.size()-1];
            hashtable[data[index]] = index;
            data.erase(data.end()-1);
            hashtable.erase(hashtable.find(val));
            return true;
        }
        return false;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        return data[rand() % data.size()];
    }
    
private:
    unordered_map<int, int> hashtable;
    vector<int> data;
};
  • 在设计Remove操作的时候,我们使用了替换的原则,在准备从vector中删除某个元素时,为了确保最少的数据的位置的移动,我们可以使用,将最后的元素数据拷贝到指定的位置去,然后在删除vector中的元素,在将hashtable中的数据位置进行更改!多么的巧妙,要逐步的学会这样的设计!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment