Skip to content

Commit 26b5c18

Browse files
author
2025
committed
Update
1 parent 1c146ce commit 26b5c18

18 files changed

Lines changed: 584 additions & 9 deletions

File tree

README.md

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,60 @@
1212

1313
<b>Array</b> <br>
1414
В этом разделе чаще всего находятся находятся задачи, использующие массивы <br>
15-
[1. Two Sum](src/main/java/org/example/g0001_0100/s0001_two_sum),
16-
[14. Longest Common Prefix](src/main/java/org/example/g0001_0100/s0014_longest_common_prefix),
15+
[1. Two Sum](src/main/java/org/example/g0001_0100/s0001_two_sum)
16+
[14. Longest Common Prefix](src/main/java/org/example/g0001_0100/s0014_longest_common_prefix)
17+
[66. Plus One](src/main/java/org/example/g0001_0100/s0066_plus_one)
18+
[88. Merge Sorted Array](src/main/java/org/example/g0001_0100/s0088_merge_sorted_array)
19+
<br>
20+
21+
<b>Binary search</b> <br>
22+
Здесь помещаем задачи с бинарным поиском<br>
23+
[35. Search Insert Position](src/main/java/org/example/g0001_0100/s0035_search_insert_position)
24+
[108. Convert Sorted Array To Binary Search Tree](src/main/java/org/example/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)
25+
26+
<b>Dynamic Programming</b> <br>
27+
Динамическое программирование (DP) — это метод решения задач,
28+
которые можно разбить на похожие подзадачи. Идея в том,
29+
чтобы не считать одну и ту же подзадачу несколько раз,
30+
а сохранить её результат и использовать повторно. <br>
31+
Пример: вычисление чисел Фибоначчи. Вместо того, чтобы каждый
32+
раз вычислять число заново, мы запоминаем уже посчитанные значения
33+
и берём их из памяти.<br>
34+
В Java обычно делают так: создают массив или таблицу для хранения результатов подзадач,
35+
заполняют этот массив постепенно, начиная с самых простых случаев,
36+
используют сохранённые результаты для решения более сложных задач.<br>
37+
1738

1839
<b>Hash Table</b><br>
1940
В этом разделе находятся задачи, использующие для решения хеш таблицы,<br>
2041
например HashMap<br>
21-
[1. Two Sum](src/main/java/org/example/g0001_0100/s0001_two_sum),
42+
[1. Two Sum](src/main/java/org/example/g0001_0100/s0001_two_sum)
43+
44+
<b>Math - математические структуры</b><br>
45+
[118. Pascals Triangle](src/main/java/org/example/g0101_0200/s0118_pascals_triangle)
46+
[119. Pascals Triangle II](src/main/java/org/example/g0101_0200/s0119_pascals_triangle_ii)
47+
48+
2249

2350
<b>Pointers - Указатели</b><br>
24-
Здесь указываем задачи, которые используют указатели для решения задачи<br>
25-
[26. Remove Duplicates From Sorted Array](src/main/java/org/example/g0001_0100/s0026_remove_duplicates_from_sorted_array),
26-
[27. Remove Element](src/main/java/org/example/g0001_0100/s0027_remove_element),
51+
Здесь указываем задачи, которые используют указатели для решения задач<br>
52+
[26. Remove Duplicates From Sorted Array](src/main/java/org/example/g0001_0100/s0026_remove_duplicates_from_sorted_array)
53+
[27. Remove Element](src/main/java/org/example/g0001_0100/s0027_remove_element)
2754

2855

56+
<b>Recursion - Рекурсия</b><br>
57+
Сюда помещаем примеры задач, использующих рекурсию
58+
[108. Convert Sorted Array To Binary Search Tree](src/main/java/org/example/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)
2959

3060

3161
<b>String</b><br>
3262
В этом разделе находятся задачи, использующие строки<br>
33-
[14. Longest Common Prefix](src/main/java/org/example/g0001_0100/s0014_longest_common_prefix),
34-
35-
63+
[14. Longest Common Prefix](src/main/java/org/example/g0001_0100/s0014_longest_common_prefix)
3664

65+
<b>Tree</b><br>
66+
Здесь помещаем задачи, которые используют деревья для решения,<br>
67+
например TreeNode.<br>
68+
[108. Convert Sorted Array To Binary Search Tree](src/main/java/org/example/g0101_0200/s0108_convert_sorted_array_to_binary_search_tree)
3769

3870

3971

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package org.example.g0001_0100.s0066_plus_one;
2+
3+
/**
4+
* LeetCode Easy
5+
* Нужно вернуть массив увеличенный на 1
6+
* [1, 2, 3] → [1, 2, 4] (123 + 1 = 124)
7+
* или добавить 1 и вернуть новый массив
8+
* [9, 9, 9] → [1, 0, 0, 0] (999 + 1 = 1000)
9+
*/
10+
public class Solution {
11+
public int[] plusOne(int[] digits) {
12+
int n = digits.length;
13+
14+
//идем от конца массива к началу
15+
for (int i = n - 1; i >= 0; i--) {
16+
// если цифры обычные, увеличиваем на 1
17+
if (digits[i] < 9) {
18+
digits[i]++;
19+
return digits;
20+
} else {
21+
digits[i] = 0;
22+
}
23+
}
24+
25+
// Если последняя (первая) цифра была 9 - попадаем сюда
26+
int[] newDigits = new int[n + 1];
27+
newDigits[0] = 1;
28+
return newDigits;
29+
}
30+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.
2+
3+
Increment the large integer by one and return _the resulting array of digits_.
4+
5+
**Example 1:**
6+
7+
**Input:** digits = [1,2,3]
8+
9+
**Output:** [1,2,4]
10+
11+
**Explanation:** The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4].
12+
13+
**Example 2:**
14+
15+
**Input:** digits = [4,3,2,1]
16+
17+
**Output:** [4,3,2,2]
18+
19+
**Explanation:** The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus, the result should be [4,3,2,2].
20+
21+
**Example 3:**
22+
23+
**Input:** digits = [0]
24+
25+
**Output:** [1]
26+
27+
**Explanation:** The array represents the integer 0. Incrementing by one gives 0 + 1 = 1. Thus, the result should be [1].
28+
29+
**Example 4:**
30+
31+
**Input:** digits = [9]
32+
33+
**Output:** [1,0]
34+
35+
**Explanation:** The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus, the result should be [1,0].
36+
37+
**Constraints:**
38+
39+
* `1 <= digits.length <= 100`
40+
* `0 <= digits[i] <= 9`
41+
* `digits` does not contain any leading `0`'s.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package org.example.g0001_0100.s0070_climbing_stairs;
2+
3+
/**
4+
* Задача: вам нужно подняться по лестнице из n ступенек.
5+
* Каждый раз вы можете сделать либо 1 шаг, либо 2 шага.
6+
* Сколько существует различных способов подняться на вершину?
7+
*
8+
* Пример:
9+
* n = 2 → 2 способа (1+1 или 2)
10+
* n = 3 → 3 способа (1+1+1, 1+2, 2+1)
11+
*
12+
* todo пока не очень понятно
13+
*/
14+
public class Solution {
15+
public int climbStairs(int n) {
16+
if (n <= 2) {
17+
return n;
18+
}
19+
20+
int[] dp = new int[n + 1];
21+
dp[1] = 1; // Один способ для 1 ступеньки
22+
dp[2] = 2; // Два способа для 2 ступенек
23+
24+
for (int i = 3; i <= n; i++) {
25+
// Количество способов для i ступенек равно сумме способов для (i-1) и (i-2)
26+
dp[i] = dp[i - 1] + dp[i - 2];
27+
}
28+
29+
return dp[n];
30+
}
31+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
**Time Complexity (Big O Time):**
2+
3+
1. The program uses dynamic programming with a loop that runs from 2 to `n-1` to fill in the `cache` array.
4+
5+
2. The loop iterates through all steps from 2 to `n-1`, and for each step `i`, it calculates the number of distinct ways by summing the values from the previous two steps (`cache[i-1]` and `cache[i-2]`).
6+
7+
3. Therefore, the loop runs in O(n) time because it iterates through all `n` steps once.
8+
9+
4. The other operations in the program, such as array assignments and comparisons, are constant time operations and do not depend on the input value `n`.
10+
11+
5. Overall, the time complexity of the program is O(n), where 'n' is the number of steps in the staircase.
12+
13+
**Space Complexity (Big O Space):**
14+
15+
1. The program uses an integer array `cache` of size `n` to store the intermediate results of the number of distinct ways to climb each step.
16+
17+
2. Therefore, the space complexity is O(n) because the space usage is directly proportional to the input value `n`.
18+
19+
3. The space complexity is dominated by the `cache` array, and it scales linearly with the size of the input staircase.
20+
21+
In summary, the time complexity of the provided program is O(n), and the space complexity is also O(n), where 'n' is the number of steps in the staircase. The program efficiently calculates the number of distinct ways to climb the staircase using dynamic programming with memoization.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
You are climbing a staircase. It takes `n` steps to reach the top.
2+
Each time you can either climb `1` or `2` steps.
3+
In how many distinct ways can you climb to the top?
4+
5+
**Example 1:**
6+
**Input:** n = 2
7+
**Output:** 2
8+
9+
**Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
10+
11+
**Example 2:**
12+
**Input:** n = 3
13+
**Output:** 3
14+
15+
**Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
16+
17+
**Constraints:**
18+
19+
* `1 <= n <= 45`
20+
21+
To solve the "Climbing Stairs" problem in Java with the Solution class, follow these steps:
22+
23+
1. Define a method `climbStairs` in the `Solution` class that takes an integer `n` as input and returns the number of distinct ways to climb to the top of the staircase with `n` steps.
24+
2. Initialize an array `dp` of size `n+1` to store the number of distinct ways to reach each step.
25+
3. Set `dp[0] = 1` and `dp[1] = 1` since there is only one way to reach the first and second steps.
26+
4. Iterate over the steps from `2` to `n`:
27+
- At each step `i`, the number of distinct ways to reach step `i` is the sum of the number of ways to reach steps `i-1` and `i-2`.
28+
- Store this sum in `dp[i]`.
29+
5. Return `dp[n]`, which represents the number of distinct ways to climb to the top of the staircase with `n` steps.
30+
31+
Here's the implementation of the `climbStairs` method in Java:
32+
33+
```java
34+
class Solution {
35+
public int climbStairs(int n) {
36+
if (n == 1) return 1;
37+
38+
int[] dp = new int[n + 1];
39+
dp[0] = 1;
40+
dp[1] = 1;
41+
42+
for (int i = 2; i <= n; i++) {
43+
dp[i] = dp[i - 1] + dp[i - 2];
44+
}
45+
46+
return dp[n];
47+
}
48+
}
49+
```
50+
51+
This implementation efficiently calculates the number of distinct ways to climb the stairs using dynamic programming, with a time complexity of O(n) and a space complexity of O(n).
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
Подходы к решению
2+
1. Рекурсия с мемоизацией
3+
Прямолинейный рекурсивный подход, но с запоминанием результатов для избежания повторных вычислений.
4+
5+
2. Динамическое программирование (оптимальное)
6+
Используем массив для хранения промежуточных результатов.
7+
8+
3. Оптимизированное ДП (константная память)
9+
Используем только несколько переменных вместо массива.
10+
11+
==============
12+
13+
Объяснение для новичка
14+
Базовые случаи:
15+
16+
Для 1 ступеньки - только 1 способ
17+
Для 2 ступенек - 2 способа (1+1 или 2)
18+
19+
Массив dp:
20+
dp[i] хранит количество способов подняться на i-ю ступеньку
21+
Каждый следующий элемент вычисляется как сумма двух предыдущих
22+
23+
Формула:
24+
dp[i] = dp[i-1] + dp[i-2]
25+
Потому что на i-ю ступеньку можно попасть либо с (i-1) (сделав 1 шаг), либо с (i-2) (сделав 2 шага)
26+
27+
Временная сложность
28+
O(n) - один проход по всем ступенькам от 3 до n.
29+
30+
Пространственная сложность
31+
O(n) - для хранения массива dp.
32+
33+
=========
34+
public class Solution {
35+
public int climbStairs(int n) {
36+
if (n <= 2) {
37+
return n;
38+
}
39+
40+
int prev1 = 1; // Для i-1
41+
int prev2 = 2; // Для i-2
42+
int current = 0;
43+
44+
for (int i = 3; i <= n; i++) {
45+
current = prev1 + prev2;
46+
prev1 = prev2;
47+
prev2 = current;
48+
}
49+
50+
return current;
51+
}
52+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.example.g0001_0100.s0088_merge_sorted_array;
2+
3+
/**
4+
* LeetCode Easy
5+
* Объединение двух отсоритированных массивов
6+
* Даны два отсортированных массива:
7+
* nums1 длиной m + n, где m — количество элементов, а n — зарезервированные нули.
8+
* nums2 длиной n.
9+
* Нужно объединить nums2 в nums1 так, чтобы итоговый массив остался отсортированным.
10+
*
11+
* Пример:
12+
* nums1 = [1, 2, 3, 0, 0, 0], m = 3
13+
* nums2 = [2, 5, 6], n = 3
14+
* Результат: [1, 2, 2, 3, 5, 6]
15+
*/
16+
public class Solution {
17+
public void merge(int[] nums1, int m, int[] nums2, int n) {
18+
// Указатель на конец реальных элементов в nums1 (не нулей)
19+
int i = m - 1;
20+
// Указатель на конец nums2
21+
int p2 = n - 1;
22+
// Указатель на конец nums1 (включая нули
23+
int j = m + n - 1;
24+
25+
// пока есть элементы в nums2
26+
while (p2 >= 0) {
27+
// Если в nums1 остались элементы И текущий в nums1 больше, чем в nums2
28+
if (i >= 0 && nums1[i] > nums2[p2]) {
29+
nums1[j--] = nums1[i--]; // Записываем элемент из nums1
30+
} else {
31+
nums1[j--] = nums2[p2--]; // Иначе записываем элемент из nums2
32+
}
33+
}
34+
}
35+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
You are given two integer arrays `nums1` and `nums2`,
2+
sorted in **non-decreasing order**, and two
3+
integers `m` and `n`, representing the number
4+
of elements in `nums1` and `nums2` respectively.
5+
6+
**Merge** `nums1` and `nums2` into a single array sorted
7+
in **non-decreasing order**.
8+
The final sorted array should not be returned by the function,
9+
but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
10+
11+
**Example 1:**
12+
**Input:** nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
13+
**Output:** [1,2,2,3,5,6]
14+
**Explanation:** The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
15+
16+
**Example 2:**
17+
**Input:** nums1 = [1], m = 1, nums2 = [], n = 0
18+
**Output:** [1]
19+
**Explanation:** The arrays we are merging are [1] and []. The result of the merge is [1].
20+
21+
**Example 3:**
22+
**Input:** nums1 = [0], m = 0, nums2 = [1], n = 1
23+
**Output:** [1]
24+
**Explanation:** The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
25+
26+
**Constraints:**
27+
28+
* `nums1.length == m + n`
29+
* `nums2.length == n`
30+
* `0 <= m, n <= 200`
31+
* `1 <= m + n <= 200`
32+
* <code>-10<sup>9</sup> <= nums1[i], nums2[j] <= 10<sup>9</sup></code>
33+
34+
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?

0 commit comments

Comments
 (0)