Skip to content

Commit ea9bdad

Browse files
committed
June 13 ques
1 parent 9ea85ef commit ea9bdad

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/540/week-2-june-8th-june-14th/3358/
2+
3+
class RandomizedSet {
4+
public:
5+
/** Initialize your data structure here. */
6+
vector<int> v;
7+
map<int, int> index_map;
8+
int size;
9+
RandomizedSet() {
10+
size = 0;
11+
}
12+
13+
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
14+
bool insert(int val) {
15+
if(index_map.find(val) != index_map.end())
16+
return false;
17+
v.push_back(val);
18+
index_map[val] = size;
19+
size++;
20+
return true;
21+
}
22+
23+
/** Removes a value from the set. Returns true if the set contained the specified element. */
24+
bool remove(int val) {
25+
if(index_map.find(val) == index_map.end())
26+
return false;
27+
int i = index_map[val];
28+
v[i] = v[size - 1];
29+
index_map[v[size - 1]] = i;
30+
31+
v.pop_back();
32+
index_map.erase(val);
33+
size--;
34+
return true;
35+
}
36+
37+
/** Get a random element from the set. */
38+
int getRandom() {
39+
int i = rand() % size;
40+
return v[i];
41+
}
42+
};
43+
44+
/**
45+
* Your RandomizedSet object will be instantiated and called as such:
46+
* RandomizedSet* obj = new RandomizedSet();
47+
* bool param_1 = obj->insert(val);
48+
* bool param_2 = obj->remove(val);
49+
* int param_3 = obj->getRandom();
50+
*/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/540/week-2-june-8th-june-14th/3357/
2+
3+
4+
class Solution {
5+
private:
6+
void swap(vector<int>& nums, int a, int b) {
7+
int temp = nums[a];
8+
nums[a] = nums[b];
9+
nums[b] = temp;
10+
}
11+
public:
12+
void sortColors(vector<int>& nums) {
13+
int l, m, h, i;
14+
l = m = 0;
15+
h = nums.size() - 1;
16+
17+
while(m <= h) {
18+
if(nums[m] == 0) {
19+
swap(nums, l++, m++);
20+
} else if (nums[m] == 1) {
21+
m++;
22+
} else if (nums[m] == 2) {
23+
swap(nums, m, h--);
24+
}
25+
}
26+
}
27+
};

0 commit comments

Comments
 (0)