0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #981: Time Based Key-Value Store

0
Posted at
class TimeMap {
    
    /** Initialize your data structure here. */
    private var timestamps = [String: [Int]]()
    private var dict = [Int: String]()
    
    func set(_ key: String, _ value: String, _ timestamp: Int) {
        timestamps[key, default: []].append(timestamp)
        dict[timestamp] = value
    }
    
    func get(_ key: String, _ timestamp: Int) -> String {
        if let ar = timestamps[key] {
            if ar[0] > timestamp {
                return ""
            }
            var start = 0
            var end = ar.count - 1
            while start <= end {
                let mid = start + (end - start) / 2
                if ar[mid] == timestamp {
                    return dict[ar[mid]]!
                } else if ar[mid] < timestamp {
                    start = mid + 1
                } else {
                    end = mid - 1
                }
            }
            return dict[ar[end]]!
        } else {
            return ""
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?