1. 程式人生 > >leetcode演算法設計第三週作業 LRU快取問題

leetcode演算法設計第三週作業 LRU快取問題

leetcode演算法設計第三週作業 LRU快取問題: https://leetcode.com/problems/lru-cache/description/ Difficulty:Hard Total Accepted:204.4K Total Submissions:955.9K

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Follow up: Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

題目看起來不難,有作業系統基礎知識的對這個應該都不陌生。 主要難在優化和對於容器的選擇上,這個關係到程式碼的效率以及關鍵函式能否達到o(1)的時間複雜度。 下面是我的第一版答案,雖然通過了但時間較慢,用了結構體陣列,每次查詢刪除的時間複雜度都為o(n),有點臃腫。

class LRUCache {
private:
	struct PointStruct
	{
		int key = INT16_MIN;
		int value = INT16_MIN;
	};
	int capacity;
	PointStruct* ps;
	int currentSize;
public:
	LRUCache(int capacity) {
		ps = new PointStruct[capacity];
		this->capacity = capacity;
		currentSize = 0;
	}
	int get(int key) {
		for (int i = currentSize-1; i >=0; i--) {
			if (ps[i].key == key) {
				PointStruct temp;
				temp.key = ps[i].key;
				temp.value = ps[i].value;
				for (int j = i; j <currentSize - 1; j++) {
					ps[j] = ps[j + 1];
				}
				ps[currentSize - 1] = temp;
				return temp.value;
			}
		}
		return -1;//not found
	}
	void put(int key, int value) {
		for (int i = currentSize - 1; i >= 0; i--) {
			if (ps[i].key == key) {
				ps[i].value = value;
				PointStruct temp;
				temp = ps[i];
				for (int j = i; j < currentSize-1; j++) {
					ps[j] = ps[j + 1];
				}
				ps[currentSize - 1] = temp;
				return;
			}
		}
		if(currentSize==capacity){
			for (int i = 0; i < currentSize - 1; i++) {
				ps[i] = ps[i + 1];
			}
			ps[capacity - 1].key = key;
			ps[capacity - 1].value = value;
		}
		else if (currentSize > capacity) {
			cout << "error" << endl;
		}
		else {
			ps[currentSize].key = key;
			ps[currentSize].value = value;
			currentSize++;
		}
		return;
	}
};

見到dalao們的高分參考後,發現有兩點差距:

  • 在程式碼段後面可以加上以下的lambda解析式提高輸入輸出效率,這個方法的關鍵在於將c++中的cin和cout的緩衝區關閉,可以顯著提升效率避免時間和速度的損失。
static const auto io_sync_off = []()
{
	// turn off sync
	std::ios::sync_with_stdio(false);
	// untie in/out streams
	std::cin.tie(nullptr);
	return nullptr;
}();
  • 結合利用list和map:
 	list <pair<int, int>> l;
    unordered_map <int, list <pair<int, int>>::iterator> mp;
  • 使用list的l.splice(l.begin(), l, x, next(x));可以將x挪到最前面。
  • 使用mp.find()可以在o(1)之內找到對應的值,將兩者結合起來,可以做到查詢和刪除的時候都可以達到o(1)的時間複雜度。 其中,unordered_map用的是雜湊函式對映,而不是map的紅黑樹,在查詢的速度上效率更高。