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

Leetcode: Summary Ranges

时间:2015-12-19 14:53:02      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 1 public class Solution {
 2     public List<String> summaryRanges(int[] nums) {
 3         List<String> res = new ArrayList<String>();
 4         if (nums==null || nums.length==0) return res;
 5         int l=0, r=0;
 6         for (; r<nums.length; r++) {
 7             if (r<nums.length-1 && nums[r]!=nums[r+1]-1 || r==nums.length-1) {
 8                 StringBuffer temp = new StringBuffer();
 9                 if (l == r) {
10                     temp.append(nums[l]);
11                     res.add(temp.toString());
12                 }
13                 else {
14                     temp.append(nums[l]);
15                     temp.append("->");
16                     temp.append(nums[r]);
17                     res.add(temp.toString());
18                 }
19                 l = r + 1;
20             }
21         }
22         return res;
23     }
24 }

 

Leetcode: Summary Ranges

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5059022.html

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