ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 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
อินพุต:
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.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก