Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 74 additions & 55 deletions content-ru/.translation-manifest.json

Large diffs are not rendered by default.

52 changes: 52 additions & 0 deletions content-ru/leetcode/Array/11-container-with-most-water.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# 11. Контейнер с наибольшим количеством воды (Medium) (<https://leetcode.com/problems/container-with-most-water/>)

> Дан целочисленный массив height длины n.
> Проведены n вертикальных линий, такие что конечные точки i-й линии — это (i, 0) и (i, height[i]).
> Найдите две линии, которые вместе с осью x образуют контейнер, содержащий максимальное количество воды.
> Верните максимальное количество воды, которое может удержать контейнер.
> Обратите внимание, что наклонять контейнер нельзя.
> Ограничения: - n == height.length - 2 <= n <= 10^5 - 0 <= height[i] <= 10^4

```ts
function maxArea(height: number[]): number {
let left = 0,
right = height.length - 1
let area = 0

while (left < right) {
const leftValue = height[left],
rightValue = height[right]
area = Math.max(area, Math.min(leftValue, rightValue) * (right - left))

if (leftValue < rightValue) {
left++
} else {
right--
}
}

return area
}

// Локальная проверка:
console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])) // 49
console.log(maxArea([1, 7, 2, 5, 4, 7, 3, 6])) // 36
console.log(maxArea([1, 1])) // 1
console.log(maxArea([2, 2, 2])) // 4
```

```md
Пример 1:

Ввод: height = [1,8,6,2,5,4,8,3,7]
Вывод: 49
Объяснение: Вышеуказанные вертикальные линии представлены массивом [1,8,6,2,5,4,8,3,7].
В этом случае максимальная площадь воды (синяя область), которую может удержать контейнер, равна 49.

Пример 2:

Ввод: height = [1,1]
Вывод: 1
```

#leetcode
71 changes: 71 additions & 0 deletions content-ru/leetcode/Array/128-longest-consecutive-sequence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# 128. Longest Consecutive Sequence (?) (<https://leetcode.com/problems/longest-consecutive-sequence/>)

> 128.
>
> Longest Consecutive Sequence (https://leetcode.com/problems/longest-consecutive-sequence/) Дан неотсортированный массив целых чисел nums, верните длину самой длинной последовательности идущих подряд элементов.
> Необходимо написать алгоритм, работающий за O(n).

```ts
function longestConsecutive(nums: number[]): number {
let maxCnt = 0,
cnt = 1
const st = new Set<number>(nums)

for (let i = 0; i < nums.length; i++) {
if (st.has(nums[i] - 1)) continue
for (let j = 1; j < nums.length + 1; j++) {
// является ли число началом последовательности?
if (st.has(nums[i] + j)) {
Comment on lines +14 to +18

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Iterate over unique values to preserve O(n).

Duplicate copies of the smallest value pass the predecessor check and each rescan the entire sequence. For example, many 1s followed by 2..50001 can make this quadratic and violate the problem’s required complexity.

Proposed fix
-  for (let i = 0; i < nums.length; i++) {
-    if (st.has(nums[i] - 1)) continue
+  for (const num of st) {
+    if (st.has(num - 1)) continue
     for (let j = 1; j < nums.length + 1; j++) {
-      if (st.has(nums[i] + j)) {
+      if (st.has(num + j)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for (let i = 0; i < nums.length; i++) {
if (st.has(nums[i] - 1)) continue
for (let j = 1; j < nums.length + 1; j++) {
// является ли число началом последовательности?
if (st.has(nums[i] + j)) {
for (const num of st) {
if (st.has(num - 1)) continue
for (let j = 1; j < nums.length + 1; j++) {
// является ли число началом последовательности?
if (st.has(num + j)) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@content-ru/leetcode/Array/128-longest-consecutive-sequence.md` around lines
12 - 16, Update the loop in the longest-consecutive-sequence solution to iterate
over unique values rather than every entry in nums, while retaining the
predecessor check and sequence scan. Use the existing set st to skip duplicate
values before processing, ensuring repeated smallest values cannot trigger
repeated full scans and the algorithm remains O(n).

cnt += 1
} else {
break
}
}
maxCnt = cnt > maxCnt ? cnt : maxCnt
cnt = 1
}
return maxCnt
}

// O(n^2) brute force
// function longestConsecutive(nums: number[]): number {
// let maxCnt = 0,
// cnt = 1
// for (let i = 0; i < nums.length; i++) {
// for (let j = 1; j < nums.length - 1; j++) {
// if (nums.includes(nums[i] + j)) {
// cnt += 1
// } else {
// break
// }
// }
// maxCnt = cnt > maxCnt ? cnt : maxCnt
// cnt = 1
// }
// return maxCnt
// };

// Local check:
console.log(longestConsecutive([100, 4, 200, 1, 3, 2])) // 4
console.log(longestConsecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1])) // 9
console.log(longestConsecutive([1, 0, 1, 2])) // 3
```

```md
Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Example 3:
Input: nums = [1,0,1,2]
Output: 3
```

#leetcode
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 1365. How Many Numbers Are Smaller Than the Current Number (Easy) (<https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number>)
# 1365. Сколько чисел меньше текущего числа (Easy) (<https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number>)

> Дан массив nums; для каждого nums[i] нужно найти, сколько чисел в массиве меньше него.
> То есть для каждого nums[i] нужно посчитать количество валидных j, таких что j != i и nums[j] < nums[i].
> Дан массив nums, для каждого nums[i] найдите, сколько чисел в массиве меньше него.
> То есть для каждого nums[i] нужно посчитать количество допустимых j, таких что j != i и nums[j] < nums[i].
> Верните ответ в виде массива.
> Ограничения: - 2 <= nums.length <= 500 - 0 <= nums[i] <= 100

Expand All @@ -19,33 +19,33 @@ function smallerNumbersThanCurrent(nums: number[]): number[] {
return nums.map((n) => firstIndex.get(n)!)
}

// Local check:
// Локальная проверка:
console.log(smallerNumbersThanCurrent([8, 1, 2, 2, 3]))
console.log(smallerNumbersThanCurrent([6, 5, 4, 8]))
console.log(smallerNumbersThanCurrent([7, 7, 7, 7]))
```

```md
Example 1:
Пример 1:

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Вход: nums = [8,1,2,2,3]
Выход: [4,0,1,1,3]
Пояснение:
Для nums[0]=8 существует четыре числа меньше него (1, 2, 2 и 3).
Для nums[1]=1 не существует ни одного числа меньше него.
Для nums[2]=2 существует одно число меньше него (1).
Для nums[3]=2 существует одно число меньше него (1).
Для nums[4]=3 существует три числа меньше него (1, 2 и 2).

Example 2:
Пример 2:

Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Вход: nums = [6,5,4,8]
Выход: [2,1,0,3]

Example 3:
Пример 3:

Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Вход: nums = [7,7,7,7]
Выход: [0,0,0,0]
```

[[leetcode/Array/1431-kids-with-the-greatest-number-of-candies]]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# 1431. Kids With the Greatest Number of Candies (Easy) (<https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/>)

> Есть n детей с конфетами.
> Дан целочисленный массив candies, где candies[i] количество конфет у i-го ребёнка, и целое число extraCandies количество дополнительных конфет, которые есть у вас.
> Верните булев массив result длины n, где result[i] равно true, если после того как i-й ребёнок получит все extraCandies, у него будет наибольшее количество конфет среди всех детей, иначе — false.
> Учтите, что наибольшее количество конфет может быть у нескольких детей одновременно.
> Вам дан целочисленный массив candies, где candies[i] обозначает количество конфет у i-го ребёнка, и целое число extraCandies, обозначающее количество дополнительных конфет, которые у вас есть.
> Верните булев массив result длины n, где result[i] равно true, если после того, как i-му ребёнку отдадут все extraCandies, у него будет наибольшее количество конфет среди всех детей, или false в противном случае.
> Обратите внимание, что несколько детей могут иметь наибольшее количество конфет.
> Ограничения: n == candies.length 2 <= n <= 100 1 <= candies[i] <= 100 1 <= extraCandies <= 50

```ts
Expand All @@ -27,40 +27,40 @@ function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
// return result
// }

// Local check:
// Локальная проверка:
console.log(kidsWithCandies([2, 3, 5, 1, 3], 3))
console.log(kidsWithCandies([4, 2, 1, 1, 2], 1))
console.log(kidsWithCandies([12, 1, 12], 10))
console.log(kidsWithCandies([1, 10, 10, 3], 1))
```

```md
Example 1:
Пример 1:

Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
Вход: candies = [2,3,5,1,3], extraCandies = 3
Выход: [true,true,true,false,true]
Объяснение: Если отдать все extraCandies:
Ребёнку 1, у него будет 2 + 3 = 5 конфет, что является наибольшим числом среди детей.
Ребёнку 2, у него будет 3 + 3 = 6 конфет, что является наибольшим числом среди детей.
Ребёнку 3, у него будет 5 + 3 = 8 конфет, что является наибольшим числом среди детей.
Ребёнку 4, у него будет 1 + 3 = 4 конфеты, что не является наибольшим числом среди детей.
Ребёнку 5, у него будет 3 + 3 = 6 конфет, что является наибольшим числом среди детей.

Example 2:
Пример 2:

Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
Вход: candies = [4,2,1,1,2], extraCandies = 1
Выход: [true,false,false,false,false]

<!-- [[leetcode/array]] [[leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number]] [[leetcode/Array/1441-build-an-array-with-stack-operations]] -->

Explanation: There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different
kid is given the extra candy.
Объяснение: Есть только 1 дополнительная конфета.
У ребёнка 1 всегда будет наибольшее количество конфет, даже если
дополнительную конфету отдать другому ребёнку.

Example 3:
Пример 3:

Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]
Вход: candies = [12,1,12], extraCandies = 10
Выход: [true,false,true]
```

[[leetcode/Array/1365-how-many-numbers-are-smaller-than-the-current-number]]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
# 1441. Build an Array With Stack Operations (Medium) (<https://leetcode.com/problems/build-an-array-with-stack-operations/>)
# 1441. Построение массива с помощью операций со стеком (Средний уровень) (<https://leetcode.com/problems/build-an-array-with-stack-operations/>)

> Дан целочисленный массив target и целое число n.
> У вас есть пустой стек с двумя операциями: - "Push": добавляет число на вершину стека.
> Вам дан целочисленный массив target и целое число n.
> У вас есть пустой стек с двумя следующими операциями: - "Push": добавляет целое число на вершину стека.
>
> - "Pop": удаляет число с вершины стека.
> Также у вас есть поток чисел из диапазона [1, n].
> Используйте эти две операции стека, чтобы числа в стеке (снизу вверх) стали равны target.
> Следуйте правилам: - Если поток чисел не пуст, возьмите следующее число из потока и положите его на вершину стека.
> - Если стек не пуст, удалите число с вершины стека.
> - Если в любой момент элементы в стеке (снизу вверх) равны target, прекратите чтение чисел из потока и операции со стеком.
> - "Pop": удаляет целое число с вершины стека.
> Также у вас есть поток целых чисел в диапазоне [1, n].
> Используйте эти две операции со стеком, чтобы числа в стеке (от дна до вершины) стали равны target.
> Вы должны следовать следующим правилам: - Если поток целых чисел не пуст, возьмите следующее целое число из потока и добавьте его на вершину стека.
> - Если стек не пуст, удалите целое число с вершины стека.
> - Если в любой момент элементы в стеке (от дна до вершины) равны target, прекратите чтение новых чисел из потока и не выполняйте больше операций со стеком.
> Верните операции со стеком, необходимые для построения target по указанным правилам.
> Если существует несколько верных ответов, верните любой из них.
> Ограничения: - 1 <= target.length <= 100 - 1 <= n <= 100 - 1 <= target[i] <= n - target строго возрастает.
> Если существует несколько допустимых ответов, верните любой из них.
> Ограничения: - 1 <= target.length <= 100 - 1 <= n <= 100 - 1 <= target[i] <= n - target строго возрастающий.

```ts
function buildArray(target: number[], n: number): string[] {
Expand Down Expand Up @@ -45,7 +45,7 @@ function buildArray(target: number[], n: number): string[] {
return operations
}

// Local check:
// Локальная проверка:
console.log(buildArray([1, 3], 3))
console.log(buildArray([1, 2, 3], 3))
console.log(buildArray([1, 2], 4))
Expand Down
6 changes: 3 additions & 3 deletions content-ru/leetcode/Array/1470-shuffle-the-array.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 1470. Shuffle the Array (Easy) (<https://leetcode.com/problems/shuffle-the-array/>)
# 1470. Перемешать массив (Easy) (<https://leetcode.com/problems/shuffle-the-array/>)

> Дан массив nums из 2n элементов в форме [x1,x2,...,xn,y1,y2,...,yn].
> Верните массив в форме [x1,y1,x2,y2,...,xn,yn].
> Дан массив nums, состоящий из 2n элементов в виде [x1,x2,...,xn,y1,y2,...,yn].
> Верните массив в виде [x1,y1,x2,y2,...,xn,yn].
> Ограничения: 1 <= n <= 500 nums.length == 2 * n 1 <= nums[i] <= 10^3

```ts
Expand Down
Loading