题目:
给你一个下标从 0 开始长度为 n 的整数数组 nums 和一个整数 target ,请你返回满足 0 <= i < j < n 且 nums[i] + nums[j] < target 的下标对 (i, j) 的数目。
思路:
乱序的数组,那只能暴力枚举了
我试着把数组排序
然后用两个指针来进行元素的求和
额...虽然能过,但是其实是错的
因为排序破坏了题目要求的“下标”关系。
我们还是不排序了,直接暴露求解吧
两个for循环,符合条件就计数加一
正确代码
var countPairs = function (nums, target) {
//只要是小于的target,就加一,不需要记录是哪两个数
let count = 0;
const len = nums.length;
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len; j++) {
if (nums[i] + nums[j] < target) {
count++;
}
}
}
return count;
};
代码:
var countPairs = function(nums, target) {
//只要是小于的target,就加一,不需要记录是哪两个数
nums.sort((a,b)=>a-b);//排序
let count = 0;
const len = nums.length;
for(let i = 0;i < len;i++){
//每次内循环都重新赋值f
let j = i + 1;
while(true){
const sum = nums[i] + nums[j];
if(sum < target){
count++;
j++;
}else{
break;
}
}
}
return count;
};