Compare commits
7 Commits
78b50806e3
...
77824baa7c
| Author | SHA1 | Date | |
|---|---|---|---|
| 77824baa7c | |||
| 807a5ae9cf | |||
| 656b5c6eb5 | |||
| a54b5b8996 | |||
| 8dcb175459 | |||
| 35c77a3a23 | |||
| f16f797381 |
@@ -0,0 +1,26 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { backspaceCompare } from "./backspaceCompare.ts";
|
||||
|
||||
describe("backspaceCompare", () => {
|
||||
|
||||
it("ab#c, ad#c => true", () => {
|
||||
expect(backspaceCompare("ab#c", "ad#c")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("ab##, c#d# => true", () => {
|
||||
expect(backspaceCompare("ab##", "c#d#")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("a#c, b => false", () => {
|
||||
expect(backspaceCompare("a#c", "b")).toBeFalsy();
|
||||
});
|
||||
|
||||
it("bxj##tw, bxj###tw => false", () => {
|
||||
expect(backspaceCompare("bxj##tw", "bxj###tw")).toBeFalsy();
|
||||
});
|
||||
|
||||
it("nzp#o#g, b#nzp#o#g => true", () => {
|
||||
expect(backspaceCompare("nzp#o#g", "b#nzp#o#g")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
function findNotSkipedIndex(s: string, i: number) {
|
||||
let skipCount = 0;
|
||||
while (i >= 0 && (skipCount > 0 || s[i] === '#')) {
|
||||
if (s[i] === '#') {
|
||||
skipCount += 1;
|
||||
i -= 1;
|
||||
continue;
|
||||
}
|
||||
skipCount -= 1;
|
||||
i -= 1;
|
||||
}
|
||||
return i;
|
||||
};
|
||||
|
||||
export function backspaceCompare(s: string, t: string): boolean {
|
||||
let sI = s.length;
|
||||
let tI = t.length;
|
||||
|
||||
while (sI > 0 && tI > 0) {
|
||||
sI = findNotSkipedIndex(s, sI - 1);
|
||||
tI = findNotSkipedIndex(t, tI - 1);
|
||||
|
||||
|
||||
if (sI >= 0 && tI >= 0 && s[sI] !== t[tI]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return findNotSkipedIndex(s, sI - 1) === findNotSkipedIndex(t, tI - 1);
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
import { backspaceCompare } from "./backspaceCompare";
|
||||
|
||||
export default backspaceCompare;
|
||||
@@ -0,0 +1,33 @@
|
||||
# backspaceCompare
|
||||
|
||||
## описание задачи
|
||||
|
||||
## тест кейсы
|
||||
|
||||
## текстовое описание решения
|
||||
|
||||
## ассимптотическая оценка
|
||||
|
||||
| Description | Estimation |
|
||||
| ----------- | ---------- |
|
||||
| time: | O(n) |
|
||||
| mem: | O(n) |
|
||||
|
||||
## time
|
||||
|
||||
| Description | Time |
|
||||
| ------------------------------------------- | ----- |
|
||||
| анализ и сбор информации | 00:00 |
|
||||
| обдумываение решения и формулировка решения | 00:00 |
|
||||
| имплементация | 00:00 |
|
||||
| исправление ошибок | 00:00 |
|
||||
| полное время затраченое на решение | 00:00 |
|
||||
|
||||
## журнал ошибок
|
||||
|
||||
## code
|
||||
|
||||
### typescript
|
||||
|
||||
ts
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import { intersectionSortedArray } from "./intersectionSortedArray";
|
||||
|
||||
export default intersectionSortedArray;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { intersectionSortedArray } from "./intersectionSortedArray.ts";
|
||||
|
||||
describe("intersectionSortedArray", () => {
|
||||
|
||||
it("[1,2,3,3,4,5,6] [3,3,5] => [3,3,5]", () => {
|
||||
expect(intersectionSortedArray([1, 2, 3, 3, 4, 5, 6], [3, 3, 5])).toEqual([3, 3, 5]);
|
||||
});
|
||||
|
||||
it("[1,2,3,4,5,6] [3,5] => [3,5]", () => {
|
||||
expect(intersectionSortedArray([1, 2, 3, 4, 5, 6], [3, 5])).toEqual([3, 5]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
export function intersectionSortedArray(a: number[], b: number[]): number[] {
|
||||
let res: number[] = [];
|
||||
let aI = 0;
|
||||
let bI = 0;
|
||||
|
||||
while (aI < a.length && bI < b.length) {
|
||||
let aValue = a[aI];
|
||||
let bValue = b[bI];
|
||||
|
||||
if (aValue === bValue) {
|
||||
res.push(aValue);
|
||||
aI++;
|
||||
bI++;
|
||||
} else {
|
||||
aValue < bValue ? aI++ : bI++;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
## hai-week-3-intersection-array
|
||||
|
||||
## описание задачи
|
||||
|
||||
Find the intersection of two **sorted** arrays **OR** in other words, given 2 sorted arrays, find all the elements which occur in both arrays.
|
||||
|
||||
**NOTE:** For the purpose of this problem ( as also conveyed by the sample case ), assume that elements that appear more than once in both arrays should be included multiple times in the final output.
|
||||
|
||||
|
||||
|
||||
**Problem Constraints**
|
||||
|
||||
1 <= **|A|** <= 106
|
||||
1 <= **|B|** <= 106
|
||||
|
||||
|
||||
|
||||
**Input Format**
|
||||
|
||||
The first argument is an integer array A.
|
||||
The second argument is an integer array B.
|
||||
|
||||
|
||||
|
||||
**Output Format**
|
||||
|
||||
Return an array of intersection of the two arrays.
|
||||
|
||||
|
||||
|
||||
**Example Input**
|
||||
|
||||
**Input 1**:
|
||||
**A**: [1 2 3 3 4 5 6]
|
||||
**B**: [3 3 5]
|
||||
|
||||
**Input 2**:
|
||||
**A**: [1 2 3 3 4 5 6]
|
||||
**B**: [3 5]
|
||||
|
||||
|
||||
|
||||
**Example Output**
|
||||
|
||||
**Output 1**: [3 3 5]
|
||||
|
||||
**Output 2**: [3 5]
|
||||
|
||||
|
||||
|
||||
**Example Explanation**
|
||||
|
||||
Explanation 1:
|
||||
|
||||
3, 3, 5 occurs in both the arrays A and B
|
||||
|
||||
Explanation 2:
|
||||
|
||||
Only 3 and 5 occurs in both the arrays A and B
|
||||
|
||||
## тест кейсы
|
||||
|
||||
## текстовое описание решения
|
||||
|
||||
## ассимптотическая оценка
|
||||
|
||||
| Description | Estimation |
|
||||
| ----------- | ------------- |
|
||||
| time: | `O(n+m)` |
|
||||
| mem: | `O(min(n,m))` |
|
||||
|
||||
## time
|
||||
|
||||
| Description | Time |
|
||||
| ------------------------------------------- | ----- |
|
||||
| анализ и сбор информации | 14:20 |
|
||||
| обдумываение решения и формулировка решения | 25:30 |
|
||||
| имплементация | 06:10 |
|
||||
| исправление ошибок | 06:12 |
|
||||
| полное время затраченое на решение | 51:14 |
|
||||
## журнал ошибок
|
||||
|
||||
- условие окончание цикла поставил `||` вместо `&&`
|
||||
- двигал указатели каждый и после условия равенства и после проверки большего меньшего, вы нес проверку в исключающуся ветвь else
|
||||
## code
|
||||
|
||||
### typescript
|
||||
|
||||
```ts
|
||||
export function intersectionSortedArray(a: number[], b: number[]): number[] {
|
||||
let res: number[] = [];
|
||||
let aI = 0;
|
||||
let bI = 0;
|
||||
|
||||
while (aI < a.length && bI < b.length) {
|
||||
let aValue = a[aI];
|
||||
let bValue = b[bI];
|
||||
|
||||
if (aValue === bValue) {
|
||||
res.push(aValue);
|
||||
aI++;
|
||||
bI++;
|
||||
} else {
|
||||
aValue < bValue ? aI++ : bI++;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
import { isPalindrome } from "./isPalindrome";
|
||||
|
||||
export default isPalindrome;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { isPalindrome } from "./isPalindrome.ts";
|
||||
|
||||
describe("isPalindrome", () => {
|
||||
it("A man, a plan, a canal: Panama => true", () => {
|
||||
expect(isPalindrome("A man, a plan, a canal: Panama")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("race a car => false", () => {
|
||||
expect(isPalindrome("race a car")).toBeFalsy();
|
||||
});
|
||||
|
||||
it(" _ => true", () => {
|
||||
expect(isPalindrome(" ")).toBeTruthy();
|
||||
});
|
||||
|
||||
it(" 0P => false", () => {
|
||||
expect(isPalindrome("0P")).toBeFalsy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
function isLetter(c: string) {
|
||||
if (/\d/.test(c)) return true;
|
||||
return c.toLowerCase() != c.toUpperCase();
|
||||
|
||||
}
|
||||
|
||||
export function isPalindrome(s: string): boolean {
|
||||
let L = 0;
|
||||
let R = s.length - 1;
|
||||
|
||||
while (L <= R) {
|
||||
let lChar = s[L].toLowerCase();
|
||||
let rChar = s[R].toLowerCase();
|
||||
|
||||
if (!isLetter(lChar)) {
|
||||
L++;
|
||||
continue;
|
||||
}
|
||||
if (!isLetter(rChar)) {
|
||||
R--;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lChar !== rChar) return false;
|
||||
L++;
|
||||
R--;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,123 @@
|
||||
# isPalindrome
|
||||
|
||||
## описание задачи
|
||||
|
||||
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
|
||||
|
||||
Given a string s, return true if it is a palindrome, or false otherwise.
|
||||
|
||||
Example 1:
|
||||
|
||||
- Input: s = "A man, a plan, a canal: Panama"
|
||||
- Output: true
|
||||
- Explanation: "amanaplanacanalpanama" is a palindrome.
|
||||
|
||||
Example 2:
|
||||
|
||||
- Input: s = "race a car"
|
||||
- Output: false
|
||||
- Explanation: "raceacar" is not a palindrome.
|
||||
|
||||
Example 3:
|
||||
|
||||
- Input: s = " "
|
||||
- Output: true
|
||||
- Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
- `1 <= s.length <= 2 * 105`
|
||||
- s consists only of printable ASCII characters.
|
||||
|
||||
## тест кейсы
|
||||
|
||||
```ts
|
||||
describe("isPalindrome", () => {
|
||||
it("A man, a plan, a canal: Panama => true", () => {
|
||||
expect(isPalindrome("A man, a plan, a canal: Panama")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("race a car => false", () => {
|
||||
expect(isPalindrome("race a car")).toBeFalsy();
|
||||
});
|
||||
|
||||
it(" _ => true", () => {
|
||||
expect(isPalindrome(" ")).toBeTruthy();
|
||||
});
|
||||
|
||||
it(" 0P => false", () => {
|
||||
expect(isPalindrome("0P")).toBeFalsy();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## текстовое описание решения
|
||||
|
||||
- я заведу два указателя которые поставлю в начало и в конец и буду двигаться в цикле пока эти указатели не пересекуться
|
||||
- в цикле я буду получать значение этих двух указателей и проверять если это буква я буду их сравнивать приведя к нижнему регистру
|
||||
- если они равны я буду двигать указатели дальше
|
||||
- если они не равны я буду возвращать false
|
||||
- перед сравнением нужно проверить что оба символа у меня буквы по условию задачи
|
||||
- если один из указателей не буква я буду двигать этот указатель пока не встречу букву
|
||||
- для проверки буква это или нет я заведу вспомогательную функцию в которой буду текущий символ приводить к нижнему и верхнему регистру и сравнивать если их значения не равны значит это буква
|
||||
|
||||
## ассимптотическая оценка
|
||||
|
||||
| Description | Estimation |
|
||||
| ----------- | ---------- |
|
||||
| time: | O(n) |
|
||||
| mem: | O(n) |
|
||||
|
||||
## time
|
||||
|
||||
| Description | Time |
|
||||
| ------------------------------------------- | ----- |
|
||||
| анализ и сбор информации | 04:18 |
|
||||
| обдумываение решения и формулировка решения | 05:40 |
|
||||
| имплементация | 10:14 |
|
||||
| исправление ошибок | 36:12 |
|
||||
| полное время затраченое на решение | 17:03 |
|
||||
|
||||
## журнал ошибок
|
||||
|
||||
- забыл инкрементировать и декрементировать указатели
|
||||
- не учел числа
|
||||
- поправил числа слетел первый кейс
|
||||
- заменил проверку чисел на регулярное выражение
|
||||
|
||||
## code
|
||||
|
||||
### typescript
|
||||
|
||||
```ts
|
||||
function isLetter(c: string) {
|
||||
if (/\d/.test(c)) return true;
|
||||
return c.toLowerCase() != c.toUpperCase();
|
||||
}
|
||||
|
||||
function isPalindrome(s: string): boolean {
|
||||
let L = 0;
|
||||
let R = s.length - 1;
|
||||
|
||||
while (L <= R) {
|
||||
let lChar = s[L].toLowerCase();
|
||||
let rChar = s[R].toLowerCase();
|
||||
|
||||
if (!isLetter(lChar)) {
|
||||
L++;
|
||||
continue;
|
||||
}
|
||||
if (!isLetter(rChar)) {
|
||||
R--;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lChar !== rChar) return false;
|
||||
L++;
|
||||
R--;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
import { maxArea } from "./maxArea";
|
||||
|
||||
export default maxArea;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { maxArea } from "./maxArea.ts";
|
||||
|
||||
describe("maxArea", () => {
|
||||
|
||||
it("[1,8,6,2,5,4,8,3,7] => 49", () => {
|
||||
expect(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])).toBe(49);
|
||||
});
|
||||
|
||||
it("[1,1] => 1", () => {
|
||||
expect(maxArea([1, 1])).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
export function maxArea(height: number[]): number {
|
||||
let L = 0;
|
||||
let R = height.length - 1;
|
||||
let res = 0;
|
||||
|
||||
while (L <= R) {
|
||||
let hL = height[L];
|
||||
let hR = height[R];
|
||||
let currArea = Math.min(hL, hR) * (R - L);
|
||||
if (currArea > res) res = currArea;
|
||||
hR > hL ? L++ : R--;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
# maxArea
|
||||
|
||||
## описание задачи
|
||||
|
||||
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
|
||||
|
||||
Find two lines that together with the x-axis form a container, such that the container contains the most water.
|
||||
|
||||
Return the maximum amount of water a container can store.
|
||||
|
||||
Notice that you may not slant the container.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
|
||||
Input: height = [1,8,6,2,5,4,8,3,7]
|
||||
Output: 49
|
||||
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
|
||||
Example 2:
|
||||
|
||||
Input: height = [1,1]
|
||||
Output: 1
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
n == height.length
|
||||
2 <= n <= 105
|
||||
0 <= height[i] <= 104
|
||||
|
||||
## тест кейсы
|
||||
|
||||
```ts
|
||||
describe("maxArea", () => {
|
||||
|
||||
it("[1,8,6,2,5,4,8,3,7] => 49", () => {
|
||||
expect(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])).toBe(49);
|
||||
});
|
||||
|
||||
it("[1,1] => 1", () => {
|
||||
expect(maxArea([1, 1])).toBe(1);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## текстовое описание решения
|
||||
|
||||
- заводим два указателя в начале и в конце
|
||||
- в цикле я буду двигаться к центру и считать площадь воды которая будет состоять из высоты столбцов и расстояния между ними
|
||||
- сравнивая высоты крайних столбцов буду решать какой указатель двигать левый или правый
|
||||
- разность между левым и правим указателем ширина площади воды минимальная высота высота площади
|
||||
|
||||
## ассимптотическая оценка
|
||||
|
||||
| Description | Estimation |
|
||||
| ----------- | ---------- |
|
||||
| time: | O(n) |
|
||||
| mem: | O(1) |
|
||||
|
||||
## time
|
||||
|
||||
| Description | Time |
|
||||
| ------------------------------------------- | ----- |
|
||||
| анализ и сбор информации | 05:00 |
|
||||
| обдумываение решения и формулировка решения | 15:12 |
|
||||
| имплементация | 05:34 |
|
||||
| исправление ошибок | 00:00 |
|
||||
| полное время затраченое на решение | 25:46 |
|
||||
|
||||
## журнал ошибок
|
||||
|
||||
## code
|
||||
|
||||
### typescript
|
||||
|
||||
```ts
|
||||
export function maxArea(height: number[]): number {
|
||||
let L = 0;
|
||||
let R = height.length - 1;
|
||||
let res = 0;
|
||||
|
||||
while (L <= R) {
|
||||
let hL = height[L];
|
||||
let hR = height[R];
|
||||
let currArea = Math.min(hL, hR) * (R - L);
|
||||
if (currArea > res) res = currArea;
|
||||
hR > hL ? L++ : R--;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
```
|
||||
@@ -0,0 +1,3 @@
|
||||
import { sortedSquares } from "./sortedSquares";
|
||||
|
||||
export default sortedSquares;
|
||||
@@ -0,0 +1,33 @@
|
||||
# sortedSquares
|
||||
|
||||
## описание задачи
|
||||
|
||||
## тест кейсы
|
||||
|
||||
## текстовое описание решения
|
||||
|
||||
## ассимптотическая оценка
|
||||
|
||||
| Description | Estimation |
|
||||
| ----------- | ---------- |
|
||||
| time: | O(n) |
|
||||
| mem: | O(n) |
|
||||
|
||||
## time
|
||||
|
||||
| Description | Time |
|
||||
| ------------------------------------------- | ----- |
|
||||
| анализ и сбор информации | 00:00 |
|
||||
| обдумываение решения и формулировка решения | 00:00 |
|
||||
| имплементация | 00:00 |
|
||||
| исправление ошибок | 00:00 |
|
||||
| полное время затраченое на решение | 00:00 |
|
||||
|
||||
## журнал ошибок
|
||||
|
||||
## code
|
||||
|
||||
### typescript
|
||||
|
||||
ts
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { sortedSquares } from "./sortedSquares.ts";
|
||||
|
||||
describe("sortedSquares", () => {
|
||||
it("[-4,-1,0,3,10] => [0,1,9,16,100]", () => {
|
||||
expect(sortedSquares([-4, -1, 0, 3, 10])).toEqual([0, 1, 9, 16, 100]);
|
||||
});
|
||||
|
||||
it("[-7,-3,2,3,11] => [4,9,9,49,121]", () => {
|
||||
expect(sortedSquares([-7, -3, 2, 3, 11])).toEqual([4, 9, 9, 49, 121]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
// export function sortedSquares(nums: number[]): number[] {
|
||||
// const result: number[] = [];
|
||||
// let L = 0;
|
||||
// let R = nums.length - 1;
|
||||
|
||||
// while (result.length !== nums.length) {
|
||||
// let leftValue = Math.pow(nums[L], 2);
|
||||
// let rightValue = Math.pow(nums[R], 2);
|
||||
|
||||
// if (leftValue > rightValue) {
|
||||
// result.push(leftValue);
|
||||
// L++;
|
||||
// } else {
|
||||
// result.push(rightValue);
|
||||
// R--
|
||||
// }
|
||||
// }
|
||||
|
||||
// return result.reverse();
|
||||
// };
|
||||
|
||||
export function sortedSquares(nums: number[]): number[] {
|
||||
const result: number[] = Array(nums.length).fill(0);
|
||||
let L = 0;
|
||||
let R = nums.length - 1;
|
||||
let indexResult = result.length - 1;
|
||||
|
||||
while (L <= R) {
|
||||
let leftValue = Math.pow(nums[L], 2);
|
||||
let rightValue = Math.pow(nums[R], 2);
|
||||
let resultValue = leftValue > rightValue ? leftValue : rightValue;
|
||||
leftValue > rightValue ? L++ : R--;
|
||||
|
||||
result[indexResult] = resultValue;
|
||||
indexResult--;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
import { twoSum } from "./twoSum";
|
||||
|
||||
export default twoSum;
|
||||
@@ -0,0 +1,114 @@
|
||||
# [twoSum](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted)
|
||||
|
||||
## описание задачи
|
||||
|
||||
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
|
||||
|
||||
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
|
||||
|
||||
The tests are generated such that there is exactly one solution. You may not use the same element twice.
|
||||
|
||||
Your solution must use only constant extra space.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
- Input: numbers = [2,7,11,15], target = 9
|
||||
- Output: [1,2]
|
||||
- Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
|
||||
|
||||
Example 2:
|
||||
|
||||
- Input: numbers = [2,3,4], target = 6
|
||||
- Output: [1,3]
|
||||
- Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
|
||||
|
||||
Example 3:
|
||||
|
||||
- Input: numbers = [-1,0], target = -1
|
||||
- Output: [1,2]
|
||||
- Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
2 <= numbers.length <= 3 * 104
|
||||
-1000 <= numbers[i] <= 1000
|
||||
numbers is sorted in non-decreasing order.
|
||||
-1000 <= target <= 1000
|
||||
The tests are generated such that there is exactly one solution.
|
||||
|
||||
## тест кейсы
|
||||
|
||||
```ts
|
||||
describe("twoSum", () => {
|
||||
|
||||
it("[2,7,11,15] 9 => [1,2]", () => {
|
||||
expect(twoSum([2, 7, 11, 15], 9)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("[2,3,4] 6 => [1,3]", () => {
|
||||
expect(twoSum([2, 3, 4], 6)).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
it("[-1, 0] -1 => [1, 2]", () => {
|
||||
expect(twoSum([-1, 0], -1)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("[5,25,75] 100 => [2,3]", () => {
|
||||
expect(twoSum([5, 25, 75], 100)).toEqual([2, 3]);
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
## текстовое описание решения
|
||||
|
||||
- заводим два указателя, в начале и конце
|
||||
- в цикле получаем по указателям значение и складываем
|
||||
- если сумма больше таргет двигаем правый указатель
|
||||
- если сумма меньше таргет двигаем левый указатель
|
||||
- если сумма равна таргет возвращаем значение указателей +1
|
||||
- если указатели сошлись а сумма не равна таргет выходим из цикла и возвращаем [-1, -1]
|
||||
|
||||
## ассимптотическая оценка
|
||||
|
||||
| Description | Estimation |
|
||||
| ----------- | ---------- |
|
||||
| time: | O(n) |
|
||||
| mem: | O(n) |
|
||||
|
||||
## time
|
||||
|
||||
| Description | Time |
|
||||
| ------------------------------------------- | ----- |
|
||||
| анализ и сбор информации | 11:50 |
|
||||
| обдумываение решения и формулировка решения | 08:47 |
|
||||
| имплементация | 20:28 |
|
||||
| исправление ошибок | 20:00 |
|
||||
| полное время затраченое на решение | 01:01:07 |
|
||||
|
||||
## журнал ошибок
|
||||
|
||||
- не разобрался с правилами для движения указателя, какой в какой момент двигать
|
||||
- не учел условие возврата индексов + 1
|
||||
|
||||
## code
|
||||
|
||||
### typescript
|
||||
|
||||
```ts
|
||||
function twoSum(numbers: number[], target: number): number[] {
|
||||
let L = 0;
|
||||
let R = numbers.length - 1;
|
||||
|
||||
while (L <= R) {
|
||||
const curSum = numbers[L] + numbers[R];
|
||||
if (curSum === target) return [L + 1, R + 1];
|
||||
curSum > target ? R-- : L++;
|
||||
}
|
||||
|
||||
return [-1, -1];
|
||||
};
|
||||
```
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { twoSum } from "./twoSum.ts";
|
||||
|
||||
describe("twoSum", () => {
|
||||
|
||||
it("[2,7,11,15] 9 => [1,2]", () => {
|
||||
expect(twoSum([2, 7, 11, 15], 9)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("[2,3,4] 6 => [1,3]", () => {
|
||||
expect(twoSum([2, 3, 4], 6)).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
it("[-1, 0] -1 => [1, 2]", () => {
|
||||
expect(twoSum([-1, 0], -1)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("[5,25,75] 100 => [2,3]", () => {
|
||||
expect(twoSum([5, 25, 75], 100)).toEqual([2, 3]);
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
export function twoSum(numbers: number[], target: number): number[] {
|
||||
let L = 0;
|
||||
let R = numbers.length - 1;
|
||||
|
||||
while (L <= R) {
|
||||
const curSum = numbers[L] + numbers[R];
|
||||
if (curSum === target) return [L + 1, R + 1];
|
||||
curSum > target ? R-- : L++;
|
||||
}
|
||||
|
||||
return [-1, -1];
|
||||
};
|
||||
Reference in New Issue
Block a user