
- Главная
- Каталог
- Интернет технологии
- C# | LeetCode
Статистика канала
Input: num = "69"
Output: true{}
using System.Text;
public class Solution {
public bool IsStrobogrammatic(string num) {
StringBuilder rotated = new StringBuilder();
for (int i = num.Length - 1; i >= 0; i--) {
char c = num[i];
if (c == '0' || c == '1' || c == '8') {
rotated.Append(c);
} else if (c == '6') {
rotated.Append('9');
} else if (c == '9') {
rotated.Append('6');
} else {
return false;
}
}
return num == rotated.ToString();
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.{}
public class Solution {
public bool HasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
Stack<TreeNode> nodeStack = new Stack<TreeNode>();
Stack<int> sumStack = new Stack<int>();
nodeStack.Push(root);
sumStack.Push(sum - root.val);
while (nodeStack.Count > 0) {
TreeNode node = nodeStack.Pop();
int currSum = sumStack.Pop();
if (node.left == null && node.right == null && currSum == 0)
return true;
if (node.left != null) {
nodeStack.Push(node.left);
sumStack.Push(currSum - node.left.val);
}
if (node.right != null) {
nodeStack.Push(node.right);
sumStack.Push(currSum - node.right.val);
}
}
return false;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]{}
public class Solution {
public int[] Intersect(int[] nums1, int[] nums2) {
Dictionary<int, int> counts = new Dictionary<int, int>();
List<int> result = new List<int>();
foreach (int num in nums1) {
if (counts.ContainsKey(num)) {
counts[num]++;
} else {
counts[num] = 1;
}
}
foreach (int num in nums2) {
if (counts.ContainsKey(num) && counts[num] > 0) {
result.Add(num);
counts[num]--;
}
}
return result.ToArray();
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: version1 = "1.2", version2 = "1.10"
Output: -1
Explanation:
version1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2.{}
public class Solution {
public int CompareVersion(string version1, string version2) {
string[] nums1 = version1.Split('.');
string[] nums2 = version2.Split('.');
int n1 = nums1.Length, n2 = nums2.Length;
int i1, i2;
for (int i = 0; i < Math.Max(n1, n2); ++i) {
i1 = i < n1 ? Int32.Parse(nums1[i]) : 0;
i2 = i < n2 ? Int32.Parse(nums2[i]) : 0;
if (i1 != i2)
return i1 > i2 ? 1 : -1;
}
return 0;
}
}{}
Ставь 👍 и забирай 📚 Базу знанийStringIterator:
- next(): Возвращает следующий символ, если в оригинальной строке еще остались несжатые символы, в противном случае возвращает пробел.
- hasNext(): Возвращает true, если в оригинальной строке остались символы, которые нужно распаковать, в противном случае возвращает false.
Пример:
Input
["StringIterator", "next", "next", "next", "next", "next", "next", "hasNext", "next", "hasNext"]
[["L1e2t1C1o1d1e1"], [], [], [], [], [], [], [], [], []]
Output
[null, "L", "e", "e", "t", "C", "o", true, "d", true]
Explanation
StringIterator stringIterator = new StringIterator("L1e2t1C1o1d1e1");
stringIterator.next(); // return "L"
stringIterator.next(); // return "e"
stringIterator.next(); // return "e"
stringIterator.next(); // return "t"
stringIterator.next(); // return "C"
stringIterator.next(); // return "o"
stringIterator.hasNext(); // return True
stringIterator.next(); // return "d"
stringIterator.hasNext(); // return True{}
public class StringIterator {
private StringBuilder res = new StringBuilder();
private int ptr = 0;
public StringIterator(string s) {
int i = 0;
while (i < s.Length) {
char ch = s[i++];
int num = 0;
while (i < s.Length && char.IsDigit(s[i])) {
num = num * 10 + (s[i] - '0');
i++;
}
for (int j = 0; j < num; j++)
res.Append(ch);
}
}
public char Next() {
return !HasNext() ? ' ' : res[ptr++];
}
public bool HasNext() {
return ptr != res.Length;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]{}
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public IList<int> GetAllElements(TreeNode root1, TreeNode root2) {
var stack1 = new Stack<TreeNode>();
var stack2 = new Stack<TreeNode>();
var output = new List<int>();
while (root1 != null || root2 != null || stack1.Count > 0 || stack2.Count > 0) {
while (root1 != null) {
stack1.Push(root1);
root1 = root1.left;
}
while (root2 != null) {
stack2.Push(root2);
root2 = root2.left;
}
if (stack2.Count == 0 || (stack1.Count > 0 && stack1.Peek().val <= stack2.Peek().val)) {
root1 = stack1.Pop();
output.Add(root1.val);
root1 = root1.right;
} else {
root2 = stack2.Pop();
output.Add(root2.val);
root2 = root2.right;
}
}
return output;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
Output: false{}
using System;
using System.Collections.Generic;
public class Solution {
public bool LeadsToDestination(int n, int[][] edges, int source, int destination) {
var graph = new Dictionary<int, List<int>>();
foreach (var edge in edges) {
if (!graph.ContainsKey(edge[0])) graph[edge[0]] = new List<int>();
graph[edge[0]].Add(edge[1]);
}
var visited = new int[n];
return Dfs(graph, visited, source, destination);
}
private bool Dfs(Dictionary<int, List<int>> graph, int[] visited, int node, int destination) {
if (visited[node] != 0) return visited[node] == 2;
if (!graph.ContainsKey(node)) return node == destination;
visited[node] = 1;
foreach (var neighbor in graph[node]) {
if (!Dfs(graph, visited, neighbor, destination)) return false;
}
visited[node] = 2;
return true;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 3
Output: 3{}
public class Solution {
public int MinSteps(int n) {
if (n == 1) return 0;
int[] dp = new int[n + 1];
for (int i = 2; i <= n; i++) {
dp[i] = i;
for (int j = 1; j <= i / 2; j++) {
if (i % j == 0) {
dp[i] = Math.Min(dp[i], dp[j] + i / j);
}
}
}
return dp[n];
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: fruits = [1,2,1]
Output: 3{}
using System;
using System.Collections.Generic;
public class Solution {
public int TotalFruit(int[] fruits) {
var basket = new Dictionary<int, int>();
int left = 0, maxFruits = 0;
for (int right = 0; right < fruits.Length; right++) {
if (!basket.ContainsKey(fruits[right])) {
basket[fruits[right]] = 0;
}
basket[fruits[right]]++;
while (basket.Count > 2) {
basket[fruits[left]]--;
if (basket[fruits[left]] == 0) {
basket.Remove(fruits[left]);
}
left++;
}
maxFruits = Math.Max(maxFruits, right - left + 1);
}
return maxFruits;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 27
Output: true
Explanation: 27 = 3^3{}
public class Solution {
public int LengthOfLongestSubstringKDistinct(string s, int k) {
int left = 0;
int right = 0;
Dictionary<char, int> charCount = new Dictionary<char, int>();
int maxLength = 0;
while (right < s.Length) {
if (!charCount.ContainsKey(s[right])) {
charCount[s[right]] = 0;
}
charCount[s[right]]++;
while (charCount.Count > k) {
charCount[s[left]]--;
if (charCount[s[left]] == 0) {
charCount.Remove(s[left]);
}
left++;
}
maxLength = Math.Max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
}{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
- Добавлен: Сначала новые
- Добавлен: Сначала старые
- Оценка: По убыванию
- Оценка: По возрастанию
Каталог Телеграм-каналов для нативных размещений
C# | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 3.4K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.8, количество отзывов – 1, со средней оценкой 5.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 2097.9 ₽, а за 1 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий