如何编写程序找出两个数组中共有的最大值?
解决两个数组交集的最大值问题
针对你的需求——生成两个包含10个1-20随机数的数组,再找出同时存在于两个数组中的最大值,分步骤解决如下:
1. 生成符合要求的随机数组
写一个可复用的函数生成数组,确保元素是1到20的整数,数组长度固定为10:
function generateRandomArray() { const arr = []; while (arr.length < 10) { const num = Math.floor(Math.random() * 20) + 1; // 若需要数组内元素不重复,可取消以下两行注释 // if (!arr.includes(num)) { arr.push(num); // } } return arr; } // 生成两个随机数组 const tab = generateRandomArray(); const tab2 = generateRandomArray();
2. 找出两个数组的交集
可以用两种方式筛选共同元素,一种是简洁的数组方法,一种是你已熟悉的循环写法:
// 方法1:用filter+includes快速筛选 const commonElements = tab.filter(num => tab2.includes(num)); // 方法2:双层for循环手动筛选 const commonElements = []; for (let i = 0; i < tab.length; i++) { const currentNum = tab[i]; for (let j = 0; j < tab2.length; j++) { if (tab2[j] === currentNum) { commonElements.push(currentNum); break; // 找到匹配项就跳出内层循环,避免重复添加 } } }
3. 求交集中的最大值
复用你已掌握的循环逻辑找最大值,同时处理交集为空的情况:
let maxCommon = 0; if (commonElements.length === 0) { console.log("两个数组没有共同元素"); } else { // 用循环遍历找最大值 maxCommon = commonElements[0]; for (let i = 1; i < commonElements.length; i++) { if (commonElements[i] > maxCommon) { maxCommon = commonElements[i]; } } // 也可以用更简洁的Math.max方法:maxCommon = Math.max(...commonElements); console.log("两个数组的共同最大值是:", maxCommon); }
结合你的示例数组的验证代码
把你的示例数组代入,可得到预期的11:
var tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20]; var tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18]; // 筛选交集 const commonElements = []; for (let i = 0; i < tab.length; i++) { for (let j = 0; j < tab2.length; j++) { if (tab[i] === tab2[j]) { commonElements.push(tab[i]); break; } } } // 找交集最大值 let max = 0; if (commonElements.length > 0) { max = commonElements[0]; for (let i = 1; i < commonElements.length; i++) { if (commonElements[i] > max) { max = commonElements[i]; } } console.log(max); // 输出11 } else { console.log("无共同元素"); }
内容的提问来源于stack exchange,提问作者katarina80
相关产品推荐
相关产品推荐

