Example #1
0
int LRUCacheMiss(vector<int> input, int maxSize) {
	typedef list<int> LI;
	typedef list<int>::iterator LII;		// key iterator 
	typedef unordered_map<int, LII> MLII;	// key, (key iterator)

	LI cache;
	MLII check;
	int count = 0;
	for (int i = 0; i < input.size(); i++) {
		if (check.count(input[i]) > 0) {
			// found in the LRU cache.
			cache.erase(check[input[i]]);
			cache.push_front(input[i]);
			check[input[i]] = cache.begin();
		}
		else {
			// not found, miss happens.
			count++;
			cache.push_front(input[i]);
			check[input[i]] = cache.begin();
			if (cache.size() > maxSize) {
				int key = cache.back();
				cache.pop_back();
				check.erase(key);
			}
		}
	}
	return count;
}
Example #2
0
    void combine(LLI &results, LI &set, int parent, int n, int k) {
        if (set.size() == k) {
            results.push_back(set);
            return;
        }

        for (int i = parent + 1; i <= n; ++i) {
            set.push_back(i);
            combine(results, set, i, n, k);
            set.pop_back();
        }
    }
Example #3
0
 void set(int key, int value) {
     auto it = cache.find(key);
     if(it!=cache.end()) {
         update(it);
     } else {
         if(used.size()==cap) {
             cache.erase(used.back());
             used.pop_back();
         }
         used.push_front(key);
     }
     cache[key] = {value, used.begin()};
 }
Example #4
0
    void fourSum(LLI &res, LI &set, const LI &nums, int lo, int target) {
        int sum = 0;
        for (const int &x : set)
            sum += x;

        if (set.size() == 4 && sum == target) {
            res.push_back(set);
            return;
        }

        if (4 <= set.size())
            return;

        for (int i = lo; i < nums.size(); ++i) {
            if (i != lo && nums[i] == nums[i - 1])
                continue;

            set.push_back(nums[i]);
            fourSum(res, set, nums, i + 1, target);
            set.pop_back();
        }
    }
Example #5
0
    void combine(LLI &results, LI &set, LI &candidates, int k, int target) {
        int sum = 0;
        for (int x : set)
            sum += x;

        if (sum == target) {
            LI sorted = set;
            sort(sorted.begin(), sorted.end());
            results.push_back(sorted);
            return;
        }

        if (target < sum)
            return;

        for (int i = k; i < candidates.size(); ++i) {
            set.push_back(candidates[i]);
            combine(results, set, candidates, i, target);
            set.pop_back();
        }
    }