题目描述
A format for expressing an ordered list of integers is to use a comma separated list of either
• individual integers
• or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, ‘-’. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example (“12, 13, 15-17”)
Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Example:
solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
// returns “-6,-3-1,3-5,7-11,14,15,17-20”
我的代码
function solution(list){
// TODO: complete solution
var str = [];
for (i = 0; i < list.length; i++) {
if ((list[i]+1) !== list[i+1]) {
//完全没有连续的情况
str += list[i].toString() + ',';
} else if ((list[i]+1) === list[i+1] && (list[i+1]+1) === list[i+2] && (list[i-1]+1) !== list[i]) {
//有2个及其以上连续的情况
str += list[i].toString() + '-';
} else if (str[str.length-1] === '-' && (list[i]+1) !== list[i+1]) {
//判断是否是range的最后一个元素
str += list[i].toString() + ',';
} else if ((list[i]-1) === list[i-1] && (list[i]+1) === list[i+1]) {
//属于range中的元素
} else if ((list[i]-1) === list[i-1] && (list[i-1]-1) === list[i-2]) {
//只有2个连续的情况
str += list[i].toString() + ',';
} else {
//新range开头
str += list[i].toString() + ',';
}
}
return str.slice(0, -1);//去掉最后的逗号
}
Clever
function solution(list){
for(var i = 0; i < list.length; i++){
var j = i;
while(list[j] - list[j+1] == -1)
j++;
if(j != i && j-i>1)
list.splice(i, j-i+1, list[i] +'-'+list[j]);
}
return list.join();
}
Key
.slice()
方法可返回一个新的数组,包含从 start 到 end (不包括该元素)的 arrayObject 中的元素。(含头不含尾)
语法:arrayObject.slice(start,end)
- 用到了
.splice()
方法,替换数组中的内容。
参数包含:(起始下标,替换长度,替换内容)
i
记录range开始位置,j
记录range结束位置。