Đề 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ụ
Đầu vào:
numbers = [1, 5, 3, 3, 4]
target = 6
Kết quả mong đợi:
expected = 2
Đầu vào:
std::vector<long long> numbers = {1, 5, 3, 3, 4};
long long target = 6;
Kết quả mong đợi:
long long expected = 2;
Đầu vào:
long[] numbers = new long[] {1, 5, 3, 3, 4};
long target = 6;
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.
Đầu vào:
numbers = [2, 2, 2]
target = 4
Kết quả mong đợi:
expected = 3
Đầu vào:
std::vector<long long> numbers = {2, 2, 2};
long long target = 4;
Kết quả mong đợi:
long long expected = 3;
Đầu vào:
long[] numbers = new long[] {2, 2, 2};
long target = 4;
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.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Check every earlier-later pair and see whether their sum matches the target.
Gợi ý 2
A straightforward double loop is enough because the input size is small.
Gợi ý 3
Be careful to count each pair once, using positions with i less than j.
Độ phức tạp mong đợi
O(n^2) time, O(1) extra space
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.