LintCode Mini Cassandra

原题网址:http://www.lintcode.com/en/problem/mini-cassandra/

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.
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")]
方法:使用哈希影射和有序影射。

/**
 * Definition of Column:
 * public class Column {
 *     public int key;
 *     public String value;
 *     public Column(int key, String value) {
 *         this.key = key;
 *         this.value = value;
 *    }
 * }
 */
public class MiniCassandra {
    private Map<String, TreeMap<Integer, String>> map = new HashMap<>();

    public MiniCassandra() {
        // initialize your data structure here.
    }
    
    /**
     * @param raw_key a string
     * @param column_start an integer
     * @param column_end an integer
     * @return void
     */
    public void insert(String raw_key, int column_key, String column_value) {
        // Write your code here
        TreeMap<Integer, String> tm = map.get(raw_key);
        if (tm == null) {
            tm = new TreeMap<>();
            map.put(raw_key, tm);
        }
        tm.put(column_key, column_value);
    }

    /**
     * @param raw_key a string
     * @param column_start an integer
     * @param column_end an integer
     * @return a list of Columns
     */
    public List<Column> query(String raw_key, int column_start, int column_end) {
        // Write your code here
        List<Column> results = new ArrayList<>();
        TreeMap<Integer, String> tm = map.get(raw_key);
        if (tm == null) return results;
        Map<Integer, String> queried = tm.subMap(column_start, true, column_end, true);
        for(int key : queried.keySet()) {
            results.add(new Column(key, queried.get(key)));
        }
        return results;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值