1、常數時間插入、刪除和獲取隨機元素
設計一個支持在平均時間複雜度 O(1)下,執行以下操作的數據結構。
insert(val):當元素 val 不存在時,向集合中插入該項。
remove(val):元素 val 存在時,從集合中移除該項。
getRandom:隨機返回現有集合中的一項。每個元素應該有相同的概率被返回。
解題思路:hashmap用來key->index(vector的索引位置),vector用來存儲key值。插入比較簡單,使用hashmap是映射索引便於在O(1)時間可以刪除vector所對應的元素。
鏈接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1/solution/shi-yong-hashmaphe-vectorshi-xian-cji-bai-93-by-zh/
class RandomizedSet {
public:
map<int,int>mymap;
vector<int>index;
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
auto it=mymap.find(val);
//存在,返回false
if(it!=mymap.end())return false;
//不存在,插入,返回true
mymap[val]=index.size();
index.push_back(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
auto it=mymap.find(val);
//不存在,返回false
if(it==mymap.end())return false;
//存在val,移出,返回ture
int size=index.size();
int loc=mymap[val];
mymap[index[size-1]]=loc;
index[loc]=index[size-1];
index.pop_back();
mymap.erase(val);
return true;
}
/** Get a random element from the set. */
int getRandom() {
int size=index.size();
if(!size)return 0;
int ind=rand()%size;
return index[ind];
}
};
/**
* 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();
*/
2、四數相加 II
給定四個包含整數的數組列表 A , B , C , D ,計算有多少個元組 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
爲了使問題簡單化,所有的 A, B, C, D 具有相同的長度 N,且 0 ≤ N ≤ 500 。所有整數的範圍在 -228 到 228 - 1 之間,最終結果不會超過 231 - 1 。
解答:哈希表 H<A[i]+B[j],計數>。對 A[i]+B[j] 的值進行計數。計算 t=C[u]+D[v]。如果 H 中有 -t,那麼, A[i]+B[j] + C[u]+D[v] == 0。multiset來模擬哈希表因爲內部用紅黑樹排序,取數時使用 count() 花費較大,用純哈希表map<int, int>就可以通過了。
作者:fxxuuu
鏈接:https://leetcode-cn.com/problems/4sum-ii/solution/c-ji-yi-hua-sou-suo-ha-xi-cha-biao-fa-by-fxxuuu/
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
if(A.empty() || B.empty() || C.empty() || D.empty())return 0;
map<int,int>ab;
for(int a:A)
{
for(int b:B)
{
ab[a+b]++;
}
}
int ans=0;
for(int c:C)
{
for(int d:D)
{
ans+=ab[-(c+d)];
}
}
return ans;
}
};