簡単 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つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" 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レビューも見ることができます。 サインインして課題を解くと議論に参加できます。