Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Count Pairs With a Sum

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

Đề bài

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
target = 6
numbers = [1, 5, 3, 3, 4]

Kết quả mong đợi:
expected = 2
Đầu vào:
long long target = 6;
std::vector<long long> numbers = {1, 5, 3, 3, 4};

Kết quả mong đợi:
long long expected = 2;
Đầu vào:
long target = 6;
long[] numbers = new long[] {1, 5, 3, 3, 4};

Kết quả mong đợi:
long expected = 2;

Giải thích

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

Ví dụ 2
Đầu vào:
target = 4
numbers = [2, 2, 2]

Kết quả mong đợi:
expected = 3
Đầu vào:
long long target = 4;
std::vector<long long> numbers = {2, 2, 2};

Kết quả mong đợi:
long long expected = 3;
Đầu vào:
long target = 4;
long[] numbers = new long[] {2, 2, 2};

Kết quả mong đợi:
long expected = 3;

Giải thích

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.