Leet Code Weekly Contest 277
1. Count Elements With Strictly Smaller and Greater Elements
Count the numbers which are strictly greater than the minimum and strictly lower than the maximum.
class Solution
{
public:
int countElements(vector<int>& nums)
{
int a = INT_MAX, b = INT_MIN;
for (auto &x : nums)
{
a = min(a, x);
b = max(b, x);
}
int ans = 0;
for (auto &x : nums)
{
if (x > a && x < b)
{
ans++;
}
}
return ans;
}
};2. Rearrange Array Elements by Sign
Naive.
class Solution
{
public:
vector<int> rearrangeArray(vector<int>& nums)
{
vector<int> a, b;
for (auto &x : nums)
{
if (x > 0)
{
a.push_back(x);
}
else
{
b.push_back(x);
}
}
vector<int> ans;
for (int i = 0, j = 0; i < a.size() || j < b.size(); )
{
if (i < a.size())
{
ans.push_back(a[i++]);
}
if (j < b.size())
{
ans.push_back(b[j++]);
}
}
return ans;
}
};3. Find All Lonely Numbers in the Array
- Hash-set.
class Solution {
public:
vector<int> findLonely(vector<int>& nums)
{
unordered_map<int, int> cnt;
for (auto &x : nums)
{
if (cnt.find(x) == cnt.end())
{
cnt[x] = 0;
}
cnt[x]++;
}
vector<int> ans;
for (auto &x : nums)
{
if (cnt[x] == 1 && cnt.find(x + 1) == cnt.end() && cnt.find(x - 1) == cnt.end())
{
ans.push_back(x);
}
}
return ans;
}
};4. Maximum Good People Based on Statements
- Enumerate every possible state of n persons (using a bit-mask).
- Valid and find the optimum one.
- Time complexity: .
class Solution {
public:
int maximumGood(vector<vector<int>>& statements)
{
int n = statements.size();
int ans = 0;
bool t[16];
for (int mask = 0; mask < (1 << n); mask++)
{
for (int i = 0; i < n; i++)
{
t[i] = (mask & (1 << i)) > 0;
}
bool valid = true;
for (int i = 0; i < n && valid; i++)
{
for (int j = 0; j < n && valid; j++)
{
if (statements[i][j] == 2)
{
continue;
}
bool s = statements[i][j] == 1;
if (t[i] && s != t[j])
{
valid = false;
}
}
}
if (valid)
{
int cnt = 0;
for (int i = 0; i < n; i++)
{
if (t[i])
{
cnt++;
}
}
ans = max(ans, cnt);
}
}
return ans;
}
};