[LintCode][System Design] Mini C

作者: 楷书 | 来源:发表于2016-03-23 04:48 被阅读882次

    Problem

    More on LeetCode Discussion

    Cassandra is a NoSQL storage. The structure has two-level keys.

    1. Level 1: raw_key. The same as hash_key or shard_key.
    2. Level 2: column_key.
    3. Level 3: column_value

    raw_key is used to hash and can not support range query. let's simplify this to a string.

    raw_key is used to hash and can not support range query. let's simplify this to a string.
    column_key is sorted and support range query. let's simplify this to integer.

    raw_key is used to hash and can not support range query. let's simplify this to a string.
    column_key is sorted and support range query. let's simplify this to integer.
    column_value is a string. you can serialize any data into a string and store it in column value.

    implement the following methods:

    1. insert(raw_key, column_key, column_value)
    2. query(raw_key, column_start, column_end) // return a list of entries

    Example

    insert("google", 1, "haha")
    query("google", 0, 1)
    >> [(1, "haha")]
    

    Solution

    map<string, map<int, string>>的方式保存数据,由于map是根据key的大小排好序的hash表,所以遍历map<int, string>时,如果key已经大于column_end则退出。

    /**
     * Definition of Column:
     * class Column {
     * public:
     *     int key;
     *     String value;
     *     Column(int key, string value) {
     *         this->key = key;
     *         this->value = value;
     *    }
     * }
     */
    class MiniCassandra {
    private:
        map<string, map<int, string>> ret;
    public:
        MiniCassandra() {
            // initialize your data structure here.
        }
    
        /**
         * @param raw_key a string
         * @param column_start an integer
         * @param column_end an integer
         * @return void
         */
        void insert(string raw_key, int column_key, string column_value) {
            // Write your code here
            ret[raw_key][column_key] = column_value;
        }
    
        /**
         * @param raw_key a string
         * @param column_start an integer
         * @param column_end an integer
         * @return a list of Columns
         */
        vector<Column> query(string raw_key, int column_start, int column_end) {
            // Write your code here
            vector<Column> q;
            for(map<int, string>::iterator iter = ret[raw_key].begin(); iter != ret[raw_key].end(); iter++) {
                if (iter->first > column_end) {
                    break;
                }
    
                if (column_start <= iter->first) {
                    q.push_back(Column(iter->first, iter->second));
                }
            }
    
            return q;
        }
    };
    

    相关文章

      网友评论

        本文标题:[LintCode][System Design] Mini C

        本文链接:https://www.haomeiwen.com/subject/dfpllttx.html