Все задачи
Легко Решено: 4 Процент решений: 80.0%

Count Pairs With a Sum

Count pairs of positions whose values add up to a target.

Чему вы научитесь

  • Check every pair of positions once
  • Start the inner loop after the outer index
  • Count matches against a target

Условие

Показать перевод

Count the pairs of different positions i < j in numbers where numbers[i] + numbers[j] equals target. Use two nested loops.

Implement count_pairs_with_sum(numbers, target).

Input

numbers: The list of integers. target: The sum to look for.

Output

Return the number of pairs.

Ограничения

0 ≤ length of numbers ≤ 500; -10,000 ≤ each number, target ≤ 10,000

Примеры

Пример 1
Ввод:
numbers = [1, 5, 3, 3, 4]
target = 6

Ожидаемый вывод:
expected = 2
Ввод:
std::vector<long long> numbers = {1, 5, 3, 3, 4};
long long target = 6;

Ожидаемый вывод:
long long expected = 2;
Ввод:
long[] numbers = new long[] {1, 5, 3, 3, 4};
long target = 6;

Ожидаемый вывод:
long expected = 2;

Пояснение

1 + 5, 3 + 3 (the two 3s at different positions) make 6: 2 pairs.

Пример 2
Ввод:
numbers = [2, 2, 2]
target = 4

Ожидаемый вывод:
expected = 3
Ввод:
std::vector<long long> numbers = {2, 2, 2};
long long target = 4;

Ожидаемый вывод:
long long expected = 3;
Ввод:
long[] numbers = new long[] {2, 2, 2};
long target = 4;

Ожидаемый вывод:
long expected = 3;

Пояснение

Every pair of the three 2s sums to 4: positions (0,1), (0,2), (1,2) = 3 pairs.

Как подступиться

Сначала попробуйте сами, затем открывайте подсказки по одной.

Подсказка 1

Check every earlier-later pair and see whether their sum matches the target.

Подсказка 2

A straightforward double loop is enough because the input size is small.

Подсказка 3

Be careful to count each pair once, using positions with i less than j.

Ожидаемая сложность

O(n^2) time, O(1) extra space

Ссылки

Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

# Участник Язык Время Память Оценка ИИ Решение
1 ННикита Python 808 ms - 5/5 Посмотреть код
2 LMLaura Mahlow Python 841 ms - 5/5 Посмотреть код
3 HJhettory Jurash Python 1,022 ms - 5/5 Посмотреть код
4 JTJohny Tran C++ 4,653 ms - 4/5 Посмотреть код

Учитесь у других

Решения сообщества

Внимание, спойлер: ниже 4 полных решений Попробуйте сначала решить сами. Вы всегда можете посмотреть код других и AI-обзоры. Войдите и решите задание, чтобы присоединиться к обсуждению.