Leet Code Weekly Contest 267
1. Time Needed to Buy Tickets
Simulate the process as descriped.
class Solution
{
public:
int timeRequiredToBuy(vector<int>& tickets, int k)
{
queue<pair<int, int>> q;
for (int i = 0; i < tickets.size(); i++)
{
q.push(make_pair(i, tickets[i]));
}
int time = 0;
while (!q.empty())
{
pair<int, int> x = q.front(); q.pop();
time++;
x.second--;
if (x.second != 0)
{
q.push(x);
}
else
{
if (x.first == k)
{
return time;
}
}
}
return 0;
}
};2. Reverse Nodes in Even Length Groups
Naive, no need to talk.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseEvenLengthGroups(ListNode* head)
{
vector<vector<int>> groups;
for (int i = 1; head != NULL; i++)
{
groups.push_back(vector<int>());
for (int j = 1; j <= i && head != NULL; j++)
{
groups.back().push_back(head->val);
head = head->next;
}
}
for (int i = 0; i < groups.size(); i++)
{
if (groups[i].size() % 2 == 0)
{
reverse(groups[i].begin(), groups[i].end());
}
}
ListNode *ret = NULL;
for (int i = groups.size() - 1; i >= 0; i--)
{
for (int j = groups[i].size() - 1; j >= 0; j--)
{
ret = new ListNode(groups[i][j], ret);
}
}
return ret;
}
};3. Decode the Slanted Ciphertext
Enumerate the positions of original text, naive.
class Solution
{
public:
string decodeCiphertext(string encodedText, int rows)
{
int cols = encodedText.length() / rows;
vector<char> chrs;
for (int i = 0; i < cols; i++)
{
for (int j = 0; i + j < cols && j < rows; j++)
{
int x = i + j, y = j;
int t = y * cols + x;
if (t < encodedText.length())
{
chrs.push_back(encodedText[t]);
}
}
}
while (chrs.size() > 0 && chrs.back() == ' ')
{
chrs.pop_back();
}
return string(chrs.begin(), chrs.end());
}
};4. Process Restricted Friend Requests
Use a disjoint-set to maintain the groups of friends. For each request , if we find a restriction where and are in the same group and and are the same group, then we reject the request.
class Solution {
public:
int fa[1000];
void init()
{
for (int i = 0; i < 1000; i++)
{
fa[i] = i;
}
}
int get_f(int x)
{
if (fa[x] == x)
{
return x;
}
return fa[x] = get_f(fa[x]);
}
unordered_set<int> targets[1000];
vector<bool> friendRequests(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests)
{
init();
for (auto r : restrictions)
{
targets[r[0]].insert(r[1]);
targets[r[1]].insert(r[0]);
}
vector<bool> ret;
for (auto req : requests)
{
bool possible = true;
int fx = get_f(req[0]), fy = get_f(req[1]);
if (fx != fy)
{
for (auto t : targets[fx])
{
if (get_f(t) == fy)
{
possible = false;
break;
}
}
}
if (!possible)
{
ret.push_back(false);
}
else
{
ret.push_back(true);
if (fx != fy)
{
fa[fx] = fy;
for (auto x : targets[fx])
{
targets[fy].insert(x);
}
}
}
}
return ret;
}
};