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

Count Pairs With a Sum

Count pairs of positions whose values add up to 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
Ввод:
target = 6
numbers = [1, 5, 3, 3, 4]

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

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

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

Пояснение

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

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

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

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

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

Пояснение

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

Ссылки

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

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

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

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.