

- Главная
- Каталог
- Интернет технологии
- Java | LeetCode
Статистика канала
Полная статистикаchevron_right
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.{}
public class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if (n == 1) return Collections.singletonList(0);
List<Set<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new HashSet<>());
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
adj.get(edge[1]).add(edge[0]);
}
List<Integer> leaves = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (adj.get(i).size() == 1) leaves.add(i);
}
int remainingNodes = n;
while (remainingNodes > 2) {
remainingNodes -= leaves.size();
List<Integer> newLeaves = new ArrayList<>();
for (int leaf : leaves) {
int neighbor = adj.get(leaf).iterator().next();
adj.get(neighbor).remove(leaf);
if (adj.get(neighbor).size() == 1) newLeaves.add(neighbor);
}
leaves = newLeaves;
}
return leaves;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input
["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
Output
[null, true, true, true, false, 2, true, true, true, 4]{}
public class MyCircularDeque {
private int[] deque;
private int front;
private int rear;
private int size;
private int capacity;
public MyCircularDeque(int k) {
this.capacity = k;
this.deque = new int[k];
this.front = 0;
this.rear = 0;
this.size = 0;
}
public boolean insertFront(int value) {
if (isFull()) return false;
front = (front - 1 + capacity) % capacity;
deque[front] = value;
size++;
return true;
}
public boolean insertLast(int value) {
if (isFull()) return false;
deque[rear] = value;
rear = (rear + 1) % capacity;
size++;
return true;
}
public boolean deleteFront() {
if (isEmpty()) return false;
front = (front + 1) % capacity;
size--;
return true;
}
public boolean deleteLast() {
if (isEmpty()) return false;
rear = (rear - 1 + capacity) % capacity;
size--;
return true;
}
public int getFront() {
if (isEmpty()) return -1;
return deque[front];
}
public int getRear() {
if (isEmpty()) return -1;
return deque[(rear - 1 + capacity) % capacity];
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: s = "aba"
Output: true{}
class Solution {
private boolean checkPalindrome(String s, int i, int j) {
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public boolean validPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return checkPalindrome(s, i, j - 1) || checkPalindrome(s, i + 1, j);
}
i++;
j--;
}
return true;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]{}
public class Solution {
private int index = 0;
public TreeNode bstFromPreorder(int[] preorder) {
return constructBST(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private TreeNode constructBST(int[] preorder, int lower, int upper) {
if (index == preorder.length) {
return null;
}
int val = preorder[index];
if (val < lower || val > upper) {
return null;
}
index++;
TreeNode root = new TreeNode(val);
root.left = constructBST(preorder, lower, val);
root.right = constructBST(preorder, val, upper);
return root;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2
Output: 20{}
public class Solution {
public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
return Math.max(maxSumNonOverlap(nums, firstLen, secondLen), maxSumNonOverlap(reverse(nums), secondLen, firstLen));
}
private int maxSumNonOverlap(int[] nums, int firstLen, int secondLen) {
int n = nums.length;
int[] prefix = new int[n + 1];
for (int i = 0; i < n; ++i) {
prefix[i + 1] = prefix[i] + nums[i];
}
int[] maxFirst = new int[n];
for (int i = firstLen - 1; i < n; ++i) {
maxFirst[i] = Math.max((i > 0 ? maxFirst[i - 1] : 0), prefix[i + 1] - prefix[i + 1 - firstLen]);
}
int[] maxSecond = new int[n];
for (int i = secondLen - 1; i < n; ++i) {
maxSecond[i] = Math.max((i > 0 ? maxSecond[i - 1] : 0), prefix[i + 1] - prefix[i + 1 - secondLen]);
}
int maxSum = 0;
for (int i = firstLen + secondLen - 1; i < n; ++i) {
maxSum = Math.max(maxSum, maxFirst[i - secondLen] + (prefix[i + 1] - prefix[i + 1 - secondLen]));
}
return maxSum;
}
private int[] reverse(int[] nums) {
int n = nums.length;
int[] reversed = new int[n];
for (int i = 0; i < n; ++i) {
reversed[i] = nums[n - i - 1];
}
return reversed;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: words = ["area","lead","wall","lady","ball"]
Output: [["ball","area","lead","lady"],["wall","area","lead","lady"]]
Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).{}
class Solution {
int N = 0;
String[] words = null;
HashMap<String, List<String>> prefixHashTable = null;
public List<List<String>> wordSquares(String[] words) {
this.words = words;
this.N = words[0].length();
List<List<String>> results = new ArrayList<>();
this.buildPrefixHashTable(words);
for (String word : words) {
LinkedList<String> wordSquares = new LinkedList<>();
wordSquares.addLast(word);
this.backtracking(1, wordSquares, results);
}
return results;
}
protected void backtracking(int step, LinkedList<String> wordSquares, List<List<String>> results) {
if (step == N) {
results.add(new ArrayList<>(wordSquares));
return;
}
StringBuilder prefix = new StringBuilder();
for (String word : wordSquares) {
prefix.append(word.charAt(step));
}
for (String candidate : this.getWordsWithPrefix(prefix.toString())) {
wordSquares.addLast(candidate);
this.backtracking(step + 1, wordSquares, results);
wordSquares.removeLast();
}
}
protected void buildPrefixHashTable(String[] words) {
this.prefixHashTable = new HashMap<>();
for (String word : words) {
for (int i = 1; i < this.N; ++i) {
String prefix = word.substring(0, i);
List<String> wordList = this.prefixHashTable.get(prefix);
if (wordList == null) {
wordList = new ArrayList<>();
wordList.add(word);
this.prefixHashTable.put(prefix, wordList);
} else {
wordList.add(word);
}
}
}
}
protected List<String> getWordsWithPrefix(String prefix) {
List<String> wordList = this.prefixHashTable.get(prefix);
return (wordList != null ? wordList : new ArrayList<>());
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.{}
public class Solution {
public int maximumGap(int[] nums) {
if (
nums == null || nums.length < 2
) return 0;
Arrays.sort(nums);
int maxGap = 0;
for (int i = 0; i < nums.length - 1; i++) maxGap = Math.max(
nums[i + 1] - nums[i],
maxGap
);
return maxGap;
}
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input:
ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0]
Output: 3{}
public class Solution {
public int countShips(Sea sea, Point topRight, Point bottomLeft) {
if (!sea.hasShips(topRight, bottomLeft)) {
return 0;
}
if (topRight.x == bottomLeft.x && topRight.y == bottomLeft.y) {
return 1;
}
int midX = (topRight.x + bottomLeft.x) / 2;
int midY = (topRight.y + bottomLeft.y) / 2;
return countShips(sea, new Point(midX, midY), bottomLeft) +
countShips(sea, topRight, new Point(midX + 1, midY + 1)) +
countShips(sea, new Point(midX, topRight.y), new Point(bottomLeft.x, midY + 1)) +
countShips(sea, new Point(topRight.x, midY), new Point(midX + 1, bottomLeft.y));
}
}{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
- Добавлен: Сначала новые
- Добавлен: Сначала старые
- Оценка: По убыванию
- Оценка: По возрастанию
Каталог Телеграм-каналов для нативных размещений
Java | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 7.1K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.7, количество отзывов – 1, со средней оценкой 5.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 2097.9 ₽, а за 7 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий