- 函数中代码的结构,三个循环结构嵌套一个分支结构
- 就是我们在看分支结构的时候,习惯了将分支结构看成一个线性的结构,也就是顺序结构,虽然执行顺序上类似线性结构,但是我们在看代码的要将其看成分支结构,如下图高亮的三个代码部分,三个高亮部分可以理解成三个并行的结构,打个比喻,一条河流走到这里,然后分成三条支流,类似一个倒着的的三叉戟结构.
function fourSum(nums: number[], target: number): number[][] {
// 对数组进行从小到大的排序
nums.sort((a, b) => a - b);
// 四个指针
let first: number = 0,
second: number,
third: number,
fourth: number;
let length: number = nums.length;
let resArr: number[][] = [];
// 第一个指针从开始遍历到最后
for (; first < length; first++) {
for (second = first + 1; second < length; second++) {
third = second + 1;
fourth = length - 1;
while (third < fourth) {
let total: number =
nums[first] + nums[second] + nums[third] + nums[fourth];
if (total === target) {
resArr.push([nums[first], nums[second], nums[third], nums[fourth]]);
third++;
fourth--;
} else if (total < target) {
third++;
} else {
fourth--;
}
}
}
}
return resArr;
}
标签:转换成,third,nums,代码,number,second,fourth,线性,first
From: https://www.cnblogs.com/zhuoss/p/16822492.html