[LeetCode][JavaScript]Summary Ranges

Summary Ranges

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"].

https://leetcode.com/problems/summary-ranges/

 

 

 


 

 

 简单的模拟题,合并连续的数字,test case排过序而且不会重复。

 1 /**
 2  * @param {number[]} nums
 3  * @return {string[]}
 4  */
 5 var summaryRanges = function(nums) {
 6     var result = [];
 7     var start = null;
 8     for(var i = 0; i < nums.length; i++){
 9         if(start === null){
10             if(!nums[i + 1] || nums[i + 1] - nums[i] !== 1){
11                 result.push(nums[i] + "");
12             }else{
13                 start = nums[i];
14             }
15         }else if(!nums[i + 1] || nums[i + 1] - nums[i] !== 1){
16             result.push(start + "->" + nums[i]);
17             start = null;
18         }
19     }    
20     return result;
21 };

 

 

 

posted @ 2015-06-26 10:29  `Liok  阅读(372)  评论(0编辑  收藏  举报