Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
使用范圍的方式描述一個已排序的數(shù)組。
很直接的實現(xiàn)戒劫,使用begin來標(biāo)記當(dāng)前范圍的起點畜伐,每遍歷到一個位置就看下一個是不是比當(dāng)前只增1棚贾,是的話index繼續(xù)后移begin不變,不是的話說明當(dāng)前范圍已經(jīng)結(jié)束霉咨,輸出一個結(jié)果谐宙,begin和index都指向下一個位置,找新的范圍:
var summaryRanges = function(nums) {
var num = nums.length;
if (num===0) return [];
var res = [];
var begin = 0;
var index = 0;
while(index+1<num) {
if (nums[index+1]-nums[index]!==1) {
if (begin === index) {
res.push("" + nums[index]);
} else {
res.push(nums[begin] + '->' + nums[index]);
}
begin = index + 1;
}
index++;
}
if (begin === index) {
res.push("" + nums[index]);
} else {
res.push(nums[begin] + '->' + nums[index]);
}
return res;
};