Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs.
A pair (i, j) is fair if:
0 <= i < j < n, and
lower <= nums[i] + nums[j] <= upper
題目說給咱一個大小為n的「零引索」整數陣列,還有兩個整數lower和upper。
目標是返回「公平對」的數量。
題目給的公平對定義:
0 <= i < j < n
lower <= nums[i] + nums[j] <= upper
我的解題思路:
class Solution {
public long countFairPairs(int[] nums, int lower, int upper) {
int count = 0; // 計算公平對
int n = nums.length;
// 遍歷每一對ij
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n ; j++) {
int sum = nums[i] + nums[j];
if (sum >= lower && sum <= upper) {
count++;
}
}
}
return count;
}
}
今天的題目很輕鬆,我甚至覺得它可以直接被劃分去easy...