问题描述:
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"
解题思路:
我一般写代码的顺序就是按照自己手工做题的顺序。当连续的数字小于3时,分别输入;当连续的数字超过3时,例如“-3,-2,-1, 0, 1”记做“-3-1”。
该题有两个判断(连续数字数量是否超过3,数字是否连续)
我的答案:
function solution(list){ // TODO: complete solution var flag=0; var b=[]; for (let i=0;i){ if(list[i]+1!=list[i+1]){ if(flag==0){b.push(list[i]);} if(flag==1){b.push(list[i-1]);b.push(list[i]);flag=0;} if(flag>1){b.push(list[i-flag]+"-"+list[i]);flag=0;} }else{ flag++; } } return b.join(); }
优秀答案:
(1)
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]); //从list[i]开始的连续(j-i+1)个数字换成
//list[i] +'-'+list[j]
} return list.join(); }
(2)
function solution(list){ // TODO: complete solution var res = list.slice(); for(var i = 0; i < list.length; ++i) { if(i === 0 || i === list.length - 1) continue; //忽略首尾数字 if(res[i] - 1 === list[i - 1] && res[i] + 1 === list[i + 1]) { //将满足左边比它小1,右边大1 的数字变成null res[i] = null; } } return res.toString().replace(/,{2,}/g, '-'); //将连续的至少2个的,换成-
哈哈哈。