先看题面:
随机生成一个长度为 10 的整数类型的数组,例如 [2, 10, 3, 4, 5, 11, 10, 11, 20],将其排列成一个新数组,要求新数组形式如下,例如 [[2, 3, 4, 5], [10, 11], [20]]。
看完有点懵,根据他举的例子,数组被分为了三个子数组,但分类的依据却有两种理解,1.按照区间划分,即0-9,10-19,20-29等等,依此类推,以10为阶梯进行分组。2.按照连续区间划分,大小连续的分为一组。
嗯,到底出题人咋想的,不得而知。so 管他呢,写就完了。
我们先按照第一种理解:
// IIFE 生成随机数组 var arr = (function (len) { let temp = [] for (var i = 0; i < len; i++) { temp.push(Math.floor(Math.random() * 100)); } return temp; })(10) console.log(arr); //1.排序 重写sort 排序 arr.sort((a, b) => { return a - b }) console.log(arr); //2去重 利用set不可重复性对数组进行去重 arr = [...new Set(arr)] console.log(arr); //3.区间分组 利用map的key记录阶梯索引 let map = new Map(); arr.forEach((item) => { let key = Math.floor(item / 10) let temp=map[key]; if(!temp) { temp=[]; } temp.push(item); map[key]=temp; }) let arr1=[] for(var key in map) { arr1.push(map[key]); } console.log(arr1);如果是连续区间其实也可以利用我们已经排序的优势来实现。
//4.连续分组 利用map的key记录分组索引 let map2 = new Map(); let index = 0 arr.forEach((item) => { let temp = map2[index]; if (!temp) { temp = []; temp.push(item); } else { if (item - temp[temp.length - 1] == 1) { temp.push(item); } else { index++; temp = [] temp.push(item); } } map2[index] = temp; }) let arr2 = [] for (var key in map2) { arr2.push(map2[key]); } console.log(arr2);最终效果如图
以上写法使用的算法都比较传统,有网友提出用reduce函数进行处理,等我学会了再来写一稿。
继续阅读与本文标签相同的文章
上一篇 :
深入理解Java线程状态
下一篇 :
Java描述设计模式(07):适配器模式
-
如何检测 Web 服务请求丢失问题
2026-05-18栏目: 教程
-
基于阿里云服务器ECS的建站过程
2026-05-18栏目: 教程
-
8分钟5个点让你彻底了解负载均衡
2026-05-18栏目: 教程
-
2019年9月16日,开发者社区奖励办法--8月评选结果正式公布
2026-05-18栏目: 教程
-
RocketMQ 主题扩分片后遇到的坑
2026-05-18栏目: 教程
