
- Главная
- Каталог
- Интернет технологии
- Java | LeetCode
Статистика канала
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]{}
class Solution {
public int[][] transpose(int[][] A) {
int R = A.length, C = A[0].length;
int[][] ans = new int[C][R];
for (int r = 0; r < R; ++r)
for (int c = 0; c < C; ++c)
ans[c][r] = A[r][c];
return ans;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: root = [5,10,10,null,null,2,3]
Output: true{}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public boolean checkEqualTree(TreeNode root) {
int totalSum = sumTree(root);
if (totalSum % 2 != 0) return false;
int target = totalSum / 2;
return checkSubtreeSum(root, target, root);
}
private int sumTree(TreeNode node) {
if (node == null) return 0;
return node.val + sumTree(node.left) + sumTree(node.right);
}
private boolean checkSubtreeSum(TreeNode node, int target, TreeNode root) {
if (node == null) return false;
if (node != root && sumTree(node) == target) {
return true;
}
return checkSubtreeSum(node.left, target, root) || checkSubtreeSum(node.right, target, root);
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [1,2,3,4]
Output: 1
Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.{}
class Solution {
public int minimumDeviation(int[] nums) {
PriorityQueue<Integer> evens = new PriorityQueue<>(Collections.reverseOrder());
int minimum = Integer.MAX_VALUE;
for (int num : nums) {
if (num % 2 == 0) {
evens.offer(num);
minimum = Math.min(minimum, num);
} else {
evens.offer(num * 2);
minimum = Math.min(minimum, num * 2);
}
}
int minDeviation = Integer.MAX_VALUE;
while (!evens.isEmpty()) {
int currentValue = evens.poll();
minDeviation = Math.min(minDeviation, currentValue - minimum);
if (currentValue % 2 == 0) {
evens.offer(currentValue / 2);
minimum = Math.min(minimum, currentValue / 2);
} else {
break;
}
}
return minDeviation;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: ransomNote = "a", magazine = "b"
Output: false{}
public boolean canConstruct(String ransomNote, String magazine) {
for (char c : ransomNote.toCharArray()) {
int index = magazine.indexOf(c);
if (index == -1) {
return false;
}
magazine = magazine.substring(0, index) + magazine.substring(index + 1);
}
return true;
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2{}
public class Solution {
public int countComponents(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
adj.get(edge[1]).add(edge[0]);
}
boolean[] visited = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, adj, visited);
count++;
}
}
return count;
}
private void dfs(int node, List<List<Integer>> adj, boolean[] visited) {
Stack<Integer> stack = new Stack<>();
stack.push(node);
while (!stack.isEmpty()) {
int current = stack.pop();
if (!visited[current]) {
visited[current] = true;
for (int neighbor : adj.get(current)) {
if (!visited[neighbor]) stack.push(neighbor);
}
}
}
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input:
urls = [
"http://news.yahoo.com",
"http://news.yahoo.com/news",
"http://news.yahoo.com/news/topics/",
"http://news.google.com",
"http://news.yahoo.com/us"
]
edges = [[2,0],[2,1],[3,2],[3,1],[0,4]]
startUrl = "http://news.yahoo.com/news/topics/"
Output: [
"http://news.yahoo.com",
"http://news.yahoo.com/news",
"http://news.yahoo.com/news/topics/",
"http://news.yahoo.com/us"
]{}
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
class HtmlParser {
public List<String> getUrls(String url) {
return new ArrayList<>();
}
}
public class Solution {
public List<String> crawl(String startUrl, HtmlParser htmlParser) {
String hostname = extractHostname(startUrl);
Set<String> visited = ConcurrentHashMap.newKeySet();
ExecutorService executor = Executors.newFixedThreadPool(10);
Queue<Future<?>> futures = new ConcurrentLinkedQueue<>();
visited.add(startUrl);
futures.add(executor.submit(() -> visit(startUrl, htmlParser, hostname, visited, futures, executor)));
while (!futures.isEmpty()) {
try {
futures.poll().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
return new ArrayList<>(visited);
}
private void visit(String url, HtmlParser htmlParser, String hostname, Set<String> visited, Queue<Future<?>> futures, ExecutorService executor) {
for (String nextUrl : htmlParser.getUrls(url)) {
if (extractHostname(nextUrl).equals(hostname) && visited.add(nextUrl)) {
futures.add(executor.submit(() -> visit(nextUrl, htmlParser, hostname, visited, futures, executor)));
}
}
}
private String extractHostname(String url) {
try {
URL u = new URL(url);
return u.getHost();
} catch (MalformedURLException e) {
e.printStackTrace();
return "";
}
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 1
Output: 1
Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.{}
public class Solution {
public int countOrders(int n) {
int MOD = 1_000_000_007;
long[] dp = new long[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
dp[i] = dp[i - 1] * (2 * i - 1) * i % MOD;
}
return (int) dp[n];
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 1, k = 2
Output: "10"{}
import java.util.HashSet;
import java.util.Set;
public class Solution {
public String crackSafe(int n, int k) {
Set<String> seen = new HashSet<>();
StringBuilder result = new StringBuilder();
String startNode = "0".repeat(n - 1);
dfs(startNode, k, seen, result);
result.append(startNode);
return result.toString();
}
private void dfs(String node, int k, Set<String> seen, StringBuilder result) {
for (int x = 0; x < k; x++) {
String neighbor = node + x;
if (!seen.contains(neighbor)) {
seen.add(neighbor);
dfs(neighbor.substring(1), k, seen, result);
result.append(x);
}
}
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
Output: false{}
import java.util.*;
public class Solution {
public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int[] edge : edges) {
graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
}
int[] visited = new int[n];
return dfs(graph, visited, source, destination);
}
private boolean dfs(Map<Integer, List<Integer>> 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;
for (int neighbor : graph.get(node)) {
if (!dfs(graph, visited, neighbor, destination)) {
return false;
}
}
visited[node] = 2;
return true;
}
}{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
- Добавлен: Сначала новые
- Добавлен: Сначала старые
- Оценка: По убыванию
- Оценка: По возрастанию
Каталог Телеграм-каналов для нативных размещений
Java | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 6.9K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.6, количество отзывов – 1, со средней оценкой 5.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 2237.76 ₽, а за 8 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий