贪心算法解题:先统计差异数,然后尽可能少的解决问题。
class Solution {
public:
int minimumSwap(string s1, string s2) {
int xy = 0, yx = 0;
int n = s1.size();
for (int i = 0; i < n; i++) {
char a = s1[i], b = s2[i];
if (a == 'x' and b == 'y') {
xy++;
}
if (a == 'y' and b == 'x') {
yx++;
}
}
if ((xy + yx) % 2 == 1) {
return -1;
}
return xy / 2 + yx / 2 + xy % 2 + yx % 2;
}
};
记录所有奇数的下标,然后找满足条件的个数。中间穿插多少个子数组通过数学公式可以计算得出。
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
int n = (int)nums.size();
int odd[n + 2], ans = 0, cnt = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] & 1) odd[++cnt] = i;
}
odd[0] = -1, odd[++cnt] = n;
for (int i = 1; i + k <= cnt; ++i) {
ans += (odd[i] - odd[i - 1]) * (odd[i + k] - odd[i + k - 1]);
}
return ans;
}
};
先统计一边的符号数,然后遍历让另一边满足对等。也可以从左往右一遍再从右往左筛一遍。
class Solution {
public:
string minRemoveToMakeValid(string s) {
int left = 0;
int right = count(begin(s), end(s), ')');
string ans = "";
for (auto& c : s) {
if (c == '(') {
if (right > 0) {
ans += c;
left++;
right--;
}
} else if (c == ')') {
if (left > 0) {
ans += c;
left--;
} else {
right--;
}
} else {
ans += c;
}
}
return ans;
}
};
裴蜀定理的应用。
class Solution {
public:
bool isGoodArray(vector<int>& nums) {
int divisor = nums[0];
for (int num : nums) {
divisor = gcd(divisor, num);
if (divisor == 1) {
break;
}
}
return divisor == 1;
}
};
# Write your MySQL query statement below
SELECT
product_id,
Round(SUM(sales) / SUM(units), 2) AS average_price
FROM (
SELECT
Prices.product_id AS product_id,
Prices.price * UnitsSold.units AS sales,
UnitsSold.units AS units
FROM Prices
JOIN UnitsSold ON Prices.product_id = UnitsSold.product_id
WHERE UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date
) T
GROUP BY product_id
如果x,y位置想为奇数,则x行和y列只可以有一个是奇数。因此统计各自奇数个数然后直接乘一下就可以得到答案了。
class Solution {
public:
int oddCells(int m, int n, vector<vector<int>>& indices) {
vector<int> rows(m), cols(n);
for (auto & index : indices) {
rows[index[0]]++;
cols[index[1]]++;
}
int oddx = 0, oddy = 0;
for (int i = 0; i < m; i++) {
if (rows[i] & 1) {
oddx++;
}
}
for (int i = 0; i < n; i++) {
if (cols[i] & 1) {
oddy++;
}
}
return oddx * (n - oddy) + (m - oddx) * oddy;
}
};
先判断不存在的条件,保证一定存在的情况下,采用贪心法优先满足upper/lower其中之一即可
class Solution {
public:
vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {
int n = colsum.size();
int sum = 0, two = 0;
for (int i = 0; i < n; ++i) {
if (colsum[i] == 2) {
++two;
}
sum += colsum[i];
}
if (sum != upper + lower || min(upper, lower) < two) {
return {};
}
upper -= two;
lower -= two;
vector<vector<int>> res(2, vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
if (colsum[i] == 2) {
res[0][i] = res[1][i] = 1;
} else if (colsum[i] == 1) {
if (upper > 0) {
res[0][i] = 1;
--upper;
} else {
res[1][i] = 1;
}
}
}
return res;
}
};