LC.P2824[统计和小于目标的下标对数目]

方法一:枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int countPairs(List<Integer> nums, int target) {
int ans = 0, n = nums.size();
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums.get(i) + nums.get(j) < target) {
++ans;
}
}
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(1)$

方法二:排序+二分查找

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;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(logn)$