码迷,mamicode.com
首页 > 其他好文 > 详细

Summary Ranges

时间:2015-11-01 19:17:18      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

1. Title

Summary Ranges

2.   Http address

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

3. The question

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

4 My code(AC)

 1 // Accepted
 2     public List<String> summaryRanges(int[] nums) {
 3         
 4         List<String> result = new ArrayList<String>();
 5         if ( nums == null || nums.length <=0)
 6             return result;        
 7         
 8         int len = nums.length;
 9         
10         if( len == 1)
11         {
12             result.add(nums[0]+"");
13             return result;
14         }
15         int beginIndex = 0;
16         for(int i = 1; i < len ; i++)
17         {
18             if( nums[i] != nums[i-1] + 1)
19             {
20                 if(beginIndex != i-1)
21                 {
22                     result.add("" + nums[beginIndex] + "->" + nums[i-1]);
23                 }else{
24                     result.add("" + nums[i-1]);
25                 }
26                 beginIndex = i;
27             }
28         }
29         
30         if(beginIndex != len-1)
31         {
32             result.add("" + nums[beginIndex] + "->" + nums[len-1]);
33         }else{
34             result.add("" + nums[len-1]);
35         }
36         return result;    
37     }

 

Summary Ranges

标签:

原文地址:http://www.cnblogs.com/ordili/p/4928325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!