
- Главная
- Каталог
- Интернет технологии
- C/C++ | LeetCode
C/C++ | LeetCode
Решения и разбор задач с LeetCode по языку программирования C / C++
Статистика канала
Input: grid = [" /","/ "]
Output: 2{}
class DSU {
public:
vector<int> parent;
DSU(int N) : parent(N) {
iota(parent.begin(), parent.end(), 0);
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void unionSet(int x, int y) {
parent[find(x)] = find(y);
}
};
class Solution {
public:
int regionsBySlashes(vector<string>& grid) {
int N = grid.size();
DSU dsu(4 * N * N);
for (int r = 0; r < N; ++r) {
for (int c = 0; c < N; ++c) {
int root = 4 * (r * N + c);
char val = grid[r][c];
if (val != '\\') {
dsu.unionSet(root + 0, root + 1);
dsu.unionSet(root + 2, root + 3);
}
if (val != '/') {
dsu.unionSet(root + 0, root + 2);
dsu.unionSet(root + 1, root + 3);
}
if (r + 1 < N) {
dsu.unionSet(root + 3, (root + 4 * N) + 0);
}
if (r - 1 >= 0) {
dsu.unionSet(root + 0, (root - 4 * N) + 3);
}
if (c + 1 < N) {
dsu.unionSet(root + 2, (root + 4) + 1);
}
if (c - 1 >= 0) {
dsu.unionSet(root + 1, (root - 4) + 2);
}
}
}
int ans = 0;
for (int x = 0; x < 4 * N * N; ++x) {
if (dsu.find(x) == x) {
++ans;
}
}
return ans;
}
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 7
{}
#include <vector>
#include <queue>
#include <climits>
using namespace std;
class Solution {
private:
int bfs(vector<vector<int>>& grid, int row, int col, int totalHouses) {
int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int rows = grid.size(), cols = grid[0].size();
int distanceSum = 0, housesReached = 0, steps = 0;
queue<pair<int, int>> q;
q.push({row, col});
vector<vector<bool>> vis(rows, vector<bool>(cols, false));
vis[row][col] = true;
while (!q.empty() && housesReached != totalHouses) {
int size = q.size();
while (size-- > 0) {
auto curr = q.front();
q.pop();
int r = curr.first, c = curr.second;
if (grid[r][c] == 1) {
distanceSum += steps;
housesReached++;
continue;
}
for (auto& dir : dirs) {
int nr = r + dir[0], nc = c + dir[1];
if (nr >= 0 && nc >= 0 && nr < rows && nc < cols && !vis[nr][nc] && grid[nr][nc] != 2) {
vis[nr][nc] = true;
q.push({nr, nc});
}
}
}
steps++;
}
if (housesReached != totalHouses) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 0 && vis[r][c]) grid[r][c] = 2;
}
}
return INT_MAX;
}
return distanceSum;
}
public:
int shortestDistance(vector<vector<int>>& grid) {
int minDistance = INT_MAX, rows = grid.size(), cols = grid[0].size(), totalHouses = 0;
for (const auto& row : grid) for (const auto& cell : row) if (cell == 1) totalHouses++;
for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) if (grid[r][c] == 0) minDistance = min(minDistance, bfs(grid, r, c, totalHouses));
return minDistance == INT_MAX ? -1 : minDistance;
}
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 2
Output: true{}
class Solution {
public:
bool divisorGame(int n) {
return n % 2 == 0;
}
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
Output: [[0,1],[6,7]]{}
class Solution {
public:
vector<vector<double>> removeInterval(vector<vector<double>>& intervals, vector<double>& toBeRemoved) {
vector<vector<double>> result;
for (auto& interval : intervals) {
if (interval[0] < toBeRemoved[0]) {
result.push_back({interval[0], min(interval[1], toBeRemoved[0])});
}
if (interval[1] > toBeRemoved[1]) {
result.push_back({max(interval[0], toBeRemoved[1]), interval[1]});
}
}
return result;
}
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: All subarrays are:
[8] with maximum absolute diff |8-8| = 0 <= 4.
[8,2] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
[2] with maximum absolute diff |2-2| = 0 <= 4.
[2,4] with maximum absolute diff |2-4| = 2 <= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
[4] with maximum absolute diff |4-4| = 0 <= 4.
[4,7] with maximum absolute diff |4-7| = 3 <= 4.
[7] with maximum absolute diff |7-7| = 0 <= 4.
Therefore, the size of the longest subarray is 2.{}
#include <queue>
#include <vector>
class Solution {
public:
int longestSubarray(std::vector<int>& nums, int limit) {
std::priority_queue<std::pair<int, int>> maxHeap;
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> minHeap;
int left = 0, maxLength = 0;
for (int right = 0; right < nums.size(); ++right) {
maxHeap.push({nums[right], right});
minHeap.push({nums[right], right});
while (maxHeap.top().first - minHeap.top().first > limit) {
left = std::min(maxHeap.top().second, minHeap.top().second) + 1;
while (maxHeap.top().second < left) {
maxHeap.pop();
}
while (minHeap.top().second < left) {
minHeap.pop();
}
}
maxLength = std::max(maxLength, right - left + 1);
}
return maxLength;
}
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: s = "abc"
Output: 3{}
int expandAroundCenter(const string& s, int left, int right) {
int count = 0;
while (left >= 0 && right < s.length() && s[left] == s[right]) {
count++;
left--;
right++;
}
return count;
}
int countSubstrings(string s) {
int totalCount = 0;
for (int i = 0; i < s.length(); i++) {
totalCount += expandAroundCenter(s, i, i);
totalCount += expandAroundCenter(s, i, i + 1);
}
return totalCount;
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [9,1,2,3,9], k = 3
Output: 20.00000
Explanation:
The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned nums into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.{}
class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
int N = A.size();
vector<double> P(N + 1);
for (int i = 0; i < N; ++i)
P[i + 1] = P[i] + A[i];
vector<double> dp(N);
for (int i = 0; i < N; ++i)
dp[i] = (P[N] - P[i]) / (N - i);
for (int k = 0; k < K - 1; ++k) {
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
dp[i] = max(dp[i], (P[j] - P[i]) / (j - i) + dp[j]);
}
}
}
return dp[0];
}
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input
["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]
Output
[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]{}
#include <unordered_map>
#include <vector>
class Cashier {
public:
Cashier(int n, int discount, std::vector<int>& products, std::vector<int>& prices)
: n(n), discount(discount), customerCount(0) {
for (size_t i = 0; i < products.size(); ++i) {
productsPrices[products[i]] = prices[i];
}
}
double getBill(std::vector<int>& product, std::vector<int>& amount) {
customerCount++;
double bill = 0.0;
for (size_t i = 0; i < product.size(); ++i) {
bill += productsPrices[product[i]] * amount[i];
}
if (customerCount % n == 0) {
bill *= (100.0 - discount) / 100.0;
}
return bill;
}
private:
int n;
int discount;
int customerCount;
std::unordered_map<int, int> productsPrices;
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5]
{}
class Solution {
public:
ListNode* findMiddleElement(ListNode* head) {
ListNode* prevPtr = nullptr;
ListNode* slowPtr = head;
ListNode* fastPtr = head;
while (fastPtr != nullptr && fastPtr->next != nullptr) {
prevPtr = slowPtr;
slowPtr = slowPtr->next;
fastPtr = fastPtr->next->next;
}
if (prevPtr != nullptr) {
prevPtr->next = nullptr;
}
return slowPtr;
}
TreeNode* sortedListToBST(ListNode* head) {
if (head == nullptr) {
return nullptr;
}
ListNode* mid = this->findMiddleElement(head);
TreeNode* node = new TreeNode(mid->val);
if (head == mid) {
return node;
}
node->left = this->sortedListToBST(head);
node->right = this->sortedListToBST(mid->next);
return node;
}
};{}
Ставь 👍 и забирай 📚 Базу знаний
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6]{}
/**
* 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 compare {
public:
bool operator()(ListNode* a, ListNode* b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty()) return NULL;
priority_queue<ListNode*, vector<ListNode*>, compare> minheap;
for (int i = 0; i < lists.size(); i++) {
if (lists[i] != NULL)
minheap.push(lists[i]);
}
ListNode* head = NULL;
ListNode* temp1;
while (!minheap.empty()) {
ListNode* temp = minheap.top();
minheap.pop();
if (head == NULL) {
head = temp;
temp1 = temp;
} else {
temp1->next = temp;
temp1 = temp;
}
if (temp->next != NULL) {
minheap.push(temp->next);
}
}
if (temp1 != NULL)
temp1->next = NULL;
return head;
}
};{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
всего 2 отзыва
- Добавлен: Сначала новые
- Добавлен: Сначала старые
- Оценка: По убыванию
- Оценка: По возрастанию
Каталог Телеграм-каналов для нативных размещений
C/C++ | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 3.3K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.2, количество отзывов – 2, со средней оценкой 5.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 1678.32 ₽, а за 6 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий