Tutte le sfide
Facile 4 risolte 80.0% di accettazione

Count Pairs With a Sum

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
numbers = [1, 5, 3, 3, 4]
target = 6

Output atteso:
expected = 2
Input:
std::vector<long long> numbers = {1, 5, 3, 3, 4};
long long target = 6;

Output atteso:
long long expected = 2;
Input:
long[] numbers = new long[] {1, 5, 3, 3, 4};
long target = 6;

Output atteso:
long expected = 2;

Spiegazione

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

Esempio 2
Input:
numbers = [2, 2, 2]
target = 4

Output atteso:
expected = 3
Input:
std::vector<long long> numbers = {2, 2, 2};
long long target = 4;

Output atteso:
long long expected = 3;
Input:
long[] numbers = new long[] {2, 2, 2};
long target = 4;

Output atteso:
long expected = 3;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 Н"Никита "Programmer" Python 808 ms - 5/5 Vedi il codice
2 LMLaura Mahlow Python 841 ms - 5/5 Vedi il codice
3 HJhettory Jurash Python 1,022 ms - 5/5 Vedi il codice
4 JTJohny Tran C++ 4,653 ms - 4/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 4 soluzioni complete sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.