1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public int countPairs(List<Integer> nums, int target) { nums.sort((a, b) -> a - b); int ans = 0, n = nums.size(); for (int j = 0; j < n; ++j) { int x = nums.get(j); int i = binarySearch(nums, target - x, j); ans += i; } return ans; }
private int binarySearch(List<Integer> nums, int target, int right) { int left = 0; while (left < right) { int mid = left + right >> 1; if (nums.get(mid) >= target) right = mid; else left = mid + 1; } return right; } }
|