LeetCode. Insert Delete GetRandom (巧用map与vector结合,实现O(1)复杂度)

unordered_map 底层数据结构是hash表,插入insert和删除delete都是 O(1) 时间复杂度
利用vector来实现 random() 方法,map的key保存元素值,value保存元素存在vector的数组下标
对于删除delete的数val,直接使用vector的末尾数字填充到被删除的数的位置,并且还需要修改map,将被删的数移除,并且将末尾数字在map中对应的value值修改为被填充的数组下标

#include <unordered_map>
#include <vector>
#include <time.h>
using namespace std;
class RandomizedSet {
private:
	//元素 + 数组下标
	unordered_map<int, int> map;
	vector<int> vec;
public:
	/** Initialize your data structure here. */
	RandomizedSet() {
		srand(time(0));
	}

	/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
	bool insert(int val) {
		if (map.find(val) != map.end()) {
			return false;
		}
		else {
			vec.push_back(val);
			map[val] = vec.size() - 1;
			return true;
		}
	}

	/** Removes a value from the set. Returns true if the set contained the specified element. */
	//
	// Replaces the last element with the deleted element
	bool remove(int val) {
		if (map.find(val) != map.end()) {
			int vecIndex = map[val];

			map[vec.back()] = vecIndex;
			vec[vecIndex] = vec.back();

			//save it for last before deleting it(val)
			//prevent error with only one element
			map.erase(val);
			vec.pop_back();
			return true;
		}
		else {
			return false;
		}
	}

	/** Get a random element from the set. */
	int getRandom() {
		if (vec.empty())return -1;
		return *(vec.begin() + (rand() % vec.size()));
	}
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * bool param_1 = obj.insert(val);
 * bool param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值