LeetCode Weekly Contest 283
1. Cells in a Range on an Excel Sheet
● ● ●c++class Solution
{
public:
vector<string> cellsInRange(string s)
{
vector<string> ans;
for (char r = s[0]; r <= s[3]; r++)
{
for (char c = s[1]; c <= s[4]; c++)
{
string tmp = "";
tmp.push_back(r);
tmp.push_back(c);
ans.push_back(tmp);
}
}
return ans;
}
};
2. Append K Integers With Minimal Sum
- Greedy, always take the smallest available integer.
- Gauss sum.
● ● ●c++typedef long long ll;
class Solution
{
public:
long long minimalKSum(vector<int>& nums, int k)
{
sort(nums.begin(), nums.end());
ll ans = 0;
for (ll i = 0, prev = 0; i < nums.size(); i++)
{
ll d = min(nums[i] - prev - 1, (ll) k);
if (d > 0)
{
ans += ((prev + 1) + (prev + d)) * d / 2;
k -= d;
}
prev = nums[i];
}
if (k > 0)
{
ans += (((ll) nums.back() + 1) + ((ll) nums.back() + k)) * k / 2;
}
return ans;
}
};
3. Create Binary Tree From Descriptions
● ● ●c++/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
unordered_map<int, TreeNode*> nodes;
TreeNode *getNode(int x)
{
if (nodes.find(x) == nodes.end())
{
nodes[x] = new TreeNode(x, NULL, NULL);
}
return nodes[x];
}
TreeNode* createBinaryTree(vector<vector<int>>& descriptions)
{
unordered_set<int> all, children;
for (auto &desc : descriptions)
{
int parent = desc[0], child = desc[1], isLeft = desc[2];
if (isLeft == 1)
{
getNode(parent)->left = getNode(child);
}
else
{
getNode(parent)->right = getNode(child);
}
all.insert(parent);
all.insert(child);
children.insert(child);
}
for (auto &x : all)
{
if (children.find(x) == children.end())
{
return getNode(x);
}
}
return NULL;
}
};
4. Replace Non-Coprime Numbers in Array
- LCM(x,y)=GCD(x,y)x∗y
- Bruce-force.
● ● ●c++typedef long long ll;
class Solution
{
public:
vector<int> replaceNonCoprimes(vector<int>& nums)
{
vector<int> ans;
for (auto &num : nums)
{
ans.push_back(num);
while (ans.size() >= 2)
{
int x = ans[ans.size() - 2], y = ans[ans.size() - 1];
int d = __gcd(x, y);
if (d == 1)
{
break;
}
ans[ans.size() - 2] = ((ll) x * y) / d;
ans.pop_back();
}
}
return ans;
}
};