?
?
lc658. deque 定長滑窗
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int n = arr.size();
int l = 0, r = 0;
deque<int> dq;
while (r < n) {
dq.push_back(arr[r]);
if (dq.size() > k) {
// 核心:距離相等時,優先保留較小值(即移除較大的后端)
if (abs(dq.front() - x) > abs(dq.back() - x) ||?
(abs(dq.front() - x) == abs(dq.back() - x) && dq.front() > dq.back())) {
dq.pop_front();
l++;
} else {
dq.pop_back();
}
}
r++;
}
return vector<int>(dq.begin(), dq.end());
}
};
?
?
lc17.11 雙指針
移動小的指針 盡量變大 來縮小差距
class Solution {
public:
int findClosest(vector<string>& w, string w1, string w2) {
vector<int> i1, i2;
for (int i = 0; i < w.size(); ++i)?????????
{
if (w[i] == w1)
i1.push_back(i);
else if (w[i] == w2)
i2.push_back(i);
}
int ret = INT_MAX, a = 0, b = 0;
while (a < i1.size() && b < i2.size())
{
ret = min(ret, abs(i1[a] - i2[b]));
if (i1[a] < i2[b])
a++;
else
b++;
}
return ret;
}
};
?
?
lc1780.三進制
?class Solution {
public:
bool checkPowersOfThree(int n)
{
while (n > 0) {
if (n % 3 == 2) {
? ? ? ? ? ? ?// 三進制位出現 2,無法由不同三的冪組成
return false;
}
n /= 3;
}
return true;
}
};
?