

- Главная
- Каталог
- Интернет технологии
- Java | LeetCode
Статистика канала
Полная статистикаchevron_right
Input: root = [1,2], voyage = [2,1]
Output: [-1]
Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.{}
class Solution {
List<Integer> flipped;
int index;
int[] voyage;
public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
flipped = new ArrayList<>();
index = 0;
this.voyage = voyage;
dfs(root);
if (!flipped.isEmpty() && flipped.get(0) == -1) {
flipped = new ArrayList<>(List.of(-1));
}
return flipped;
}
public void dfs(TreeNode node) {
if (node != null) {
if (node.val != voyage[index++]) {
flipped = new ArrayList<>(List.of(-1));
return;
}
if (index < voyage.length && node.left != null && node.left.val != voyage[index]) {
flipped.add(node.val);
dfs(node.right);
dfs(node.left);
} else {
dfs(node.left);
dfs(node.right);
}
}
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: strs = ["babca","bbazb"]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).
Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.{}
class Solution {
public int minDeletionSize(String[] A) {
int W = A[0].length();
int[] dp = new int[W];
Arrays.fill(dp, 1);
for (int i = W-2; i >= 0; --i)
search: for (int j = i+1; j < W; ++j) {
for (String row: A)
if (row.charAt(i) > row.charAt(j))
continue search;
dp[i] = Math.max(dp[i], 1 + dp[j]);
}
int kept = 0;
for (int x: dp)
kept = Math.max(kept, x);
return W - kept;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.{}
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n = s.length();
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
StringBuilder pattern = new StringBuilder();
for (int j = 0; j < n / i; j++) {
pattern.append(s.substring(0, i));
}
if (s.equals(pattern.toString())) {
return true;
}
}
}
return false;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: a = "aba", b = "cdc"
Output: 3
Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
Note that "cdc" is also a longest uncommon subsequence.{}
class Solution {
public int findLUSlength(String a, String b) {
if (a.equals(b)) {
return -1;
} else {
return Math.max(a.length(), b.length());
}
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.{}
class Solution {
Map<TreeNode, Integer> depth;
int maxDepth;
public TreeNode subtreeWithAllDeepest(TreeNode root) {
depth = new HashMap<>();
depth.put(null, -1);
dfs(root, null);
maxDepth = depth.values().stream().max(Integer::compare).orElse(-1);
return answer(root);
}
private void dfs(TreeNode node, TreeNode parent) {
if (node != null) {
depth.put(node, depth.get(parent) + 1);
dfs(node.left, node);
dfs(node.right, node);
}
}
private TreeNode answer(TreeNode node) {
if (node == null || depth.get(node) == maxDepth) return node;
TreeNode L = answer(node.left), R = answer(node.right);
if (L != null && R != null) return node;
return L != null ? L : R;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
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(int[] A, int K) {
int N = A.length;
double[] P = new double[N + 1];
for (int i = 0; i < N; ++i)
P[i + 1] = P[i] + A[i];
double[][] dp = new double[N][N];
for (int i = 0; i < N; ++i)
dp[i][0] = (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][0] = Math.max(dp[i][0], (P[j] - P[i]) / (j - i) + dp[j][0]);
}
}
}
return dp[0][0];
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: s = "abc", t = "ahbgdc"
Output: true{}
class Solution {
public boolean isSubsequence(String s, String t) {
int leftBound = s.length(), rightBound = t.length();
int pLeft = 0, pRight = 0;
while (pLeft < leftBound && pRight < rightBound) {
if (s.charAt(pLeft) == t.charAt(pRight)) {
pLeft += 1;
}
pRight += 1;
}
return pLeft == leftBound;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 3
Output: 3{}
class Solution {
public int findNthDigit(int n) {
int length = 1;
long count = 9;
int start = 1;
while (n > length * count) {
n -= length * count;
length++;
count *= 10;
start *= 10;
}
start += (n - 1) / length;
String s = Integer.toString(start);
return s.charAt((n - 1) % length) - '0';
}
}{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
- Добавлен: Сначала новые
- Добавлен: Сначала старые
- Оценка: По убыванию
- Оценка: По возрастанию
Каталог Телеграм-каналов для нативных размещений
Java | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 7.0K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 6.0, количество отзывов – 1, со средней оценкой 5.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 2517.48 ₽, а за 8 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий