力扣面试150(40/150)
7.24 228. 汇总区间
给定一个 无重复元素 的 有序 整数数组 nums
。
区间 [a,b]
是从 a
到 b
(包含)的所有整数的集合。
返回 *恰好覆盖数组中所有数字 的 最小有序 区间范围列表* 。也就是说,nums
的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个区间但不属于 nums
的数字 x
。
列表中的每个区间范围 [a,b]
应该按如下格式输出:
-
\"a->b\"
,如果a != b
-
\"a\"
,如果a == b
我的思路:
nums循环遍历,
start and end
start = 0
遍历,if(nums[i] === start +1) end = nums[i]
if(!) arr.push(${start} -> ${end}
)
start = nums[i + 1]
我的代码:
var summaryRanges = function(nums) { let start = nums[0]; let end = nums[0]; let ansArr = []; // 开始遍历 for(let i = 1 ; i ${end}`); } end = nums[i]; start = nums[i]; } } return ansArr;};
总结:
初始化 start 和 end 为数组的第一个数字,然后遍历数组。如果当前数字 nums[i] 是 end+1,说明是连续的,更新 end。否则,检查 start 和 end 是否相同,相同则直接加入 start,不同则加入 start->end,并更新 start 和 end 为当前数字。最后返回结果数组。最开始看到输出的格式的时候人都傻掉了,后面我灵机一动想到模板字符串,嘻嘻嘻快速通过。