You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Vasily Guzov a54b5b8996 [HAI] week3 two sum withou hashsum
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted
1 year ago
..
index.ts [HAI] week3 two sum withou hashsum 1 year ago
readme.md [HAI] week3 two sum withou hashsum 1 year ago
twoSum.test.ts [HAI] week3 two sum withou hashsum 1 year ago
twoSum.ts [HAI] week3 two sum withou hashsum 1 year ago

readme.md

twoSum

описание задачи

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.

тест кейсы

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

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];
};