2 回答
TA贡献1853条经验 获得超9个赞
let nums = [2,7,11,15]
, target = 18
, flag=0
, i, j
;
for( i=0; i<nums.length-1; i++) {
for( j=i+1; j<nums.length; j++) {
if((nums[i]+nums[j])===target) {
flag=1;
break;
}
}
if(flag) break;
}
console.log(nums[i],nums[j]);
TA贡献1877条经验 获得超6个赞
那 ?
let nums = [2,7,11,15]
, target = 18
, i, j, found = false
;
for(i=0; i<nums.length-1; i++) {
for( j=i+1; j<nums.length; j++) {
found = (nums[i]+nums[j])===target
if (found) break;
}
if (found) break;
}
if (found) console.log('values = ', nums[i],'+', nums[j], '=', target )
else console.log('none' )
您也可以这样做:
let nums = [2,7,11,15]
, target = 18
, i=0, j=1, sum = nums[i] + nums[j]
;
while (sum != target)
{
if (++j===nums.length )
if (++i===(nums.length-1)) break
else j=i+1
sum = nums[i] + nums[j]
}
if (sum===target) console.log('values = ', nums[i],'+', nums[j], '=', target )
else console.log('none' )
添加回答
举报