其他分享
首页 > 其他分享> > 2022.7.26 LeetCode

2022.7.26 LeetCode

作者:互联网

LeetCode

实现跳表

主要参考了以下几篇Bolg:
https://www.acwing.com/blog/content/15081/
https://www.jianshu.com/p/9d8296562806
https://www.acwing.com/blog/content/4863/
https://www.luogu.com.cn/blog/your-alpha1022/SkipList

class Skiplist {
	public:

		const static int MAX_LEVEL = 16, INF = 30010, N = 50010;
		float ratio = 0.5;
		struct Node {
			int down = 0, next = 0, val, maxLevel = 0;
			void init(int _val, int _maxLevel, int _down, int _next) {
				down = _down, val = _val, maxLevel = _maxLevel, next = _next;
			}
		};
		int idx = 0, head, nodes[N], tt = -1;
		Node tr[N];

		Skiplist() {
			tr[0].init(INF, 0, 0, 0);
			int u = head = getNode();
			tr[u].init(-INF, MAX_LEVEL, 0, 0);
			for (int i = MAX_LEVEL - 1; i > 0; i--) {
				int v = getNode();
				tr[u].down = v;
				tr[v].init(-INF, i, 0, 0);
				u = v;
			}
		}

		int getNode() {
			if (tt < 0)
				nodes[++tt] = ++idx;
			int u = nodes[tt--];
			return u;
		}

		void gcNode(int u) {
			nodes[++tt] = u;
		}

		int update[MAX_LEVEL + 1];
		int searchHit(int num) {
			int u = head, hit = 0, p;
			for (int level = MAX_LEVEL; level > 0; level--) {
				p = u;
				while (tr[p].val < num)
					u = p, p = tr[p].next;
				if (tr[p].val == num)
					hit = max(level, hit);
				update[level] = u;
				u = tr[u].down;
			}
			return hit;
			// 返回索引所在层级
		}



		bool search(int target) {
			return searchHit(target);
		}

		void add(int num) {
			searchHit(num);
			int last = 0, randLevel = randomLevel(), t, c, u;
			for (int level = randLevel; level > 0; level--) {
				u = getNode();
				Node &node = tr[u];
				node.init(num, level, 0, 0);
				c = update[level];
				t = tr[c].next;
				tr[c].next = u, node.next = t;
				if (last)
					tr[last].down = u;
				last = u;
			}
		}

		bool erase(int num) {
			int hit = searchHit(num);
			if (!hit)
				return false;

			int p, t;
			for (int level = hit; level > 0; level--) {
				p = update[level];
				t = tr[p].next;
				tr[p].next = tr[t].next;
				gcNode(t);
			}
			return true;
		}

		int randomLevel() {
			int level = 0;
			while (rand() % 100 < ratio * 100 && level < MAX_LEVEL) {
				level ++;
			}
			return level + 1;
		}
};

Acwing

模拟

#include <bits/stdc++.h>
using namespace std;

const int N = 2e5 + 10;

int T;
int n, k;
int w[N];

int main() {
	cin >> T;
	for (int ct = 1; ct <= T; ct++) {
		cin >> n >> k;
		for (int i = 1; i <= n; i++) {
			cin >> w[i];
		}
		int ans = 0;

		for (int i = n; i >= k; ) {
			if (w[i] == 1) {
				int t = 1;
				while (w[i] == t && t <= k) {
					i--;
					t++;
				}
				if (t == k + 1) {
					ans++;
				}
			} else {
				i--;
			}
		}

		cout << "Case #" << ct << ": " << ans << endl;
	}


	return 0;
}

标签:26,hit,level,int,tr,next,num,2022.7,LeetCode
来源: https://www.cnblogs.com/superPG/p/16519947.html