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

228. Summary Ranges

时间:2017-07-13 20:16:38      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:int   需要   str   ++   长度   连接   数字   sort   res   

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

道题给定我们一个有序数组,让我们总结区间,具体来说就是让我们找出连续的序列,然后首尾两个数字之间用个“->"来连接,那么我只需遍历一遍数组即可,每次检查下一个数是不是递增的,如果是,则继续往下遍历,如果不是了,我们还要判断此时是一个数还是一个序列,一个数直接存入结果,序列的话要存入首尾数字和箭头“->"。我们需要两个变量i和j,其中i是连续序列起始数字的位置,j是连续数列的长度,当j为1时,说明只有一个数字,若大于1,则是一个连续序列,代码如下:

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<String>();
        if (nums==null || nums.length==0) return res;
        for (int i=0; i<nums.length; i++) {
            int temp = nums[i];
            while (i+1<nums.length && nums[i+1]==nums[i]+1) i++;
            if (temp == nums[i]) {
                res.add(temp+"");
            }
            else {
                res.add(temp+"->"+nums[i]);
            }
        }
        return res;
    }
}

  

228. Summary Ranges

标签:int   需要   str   ++   长度   连接   数字   sort   res   

原文地址:http://www.cnblogs.com/apanda009/p/7162193.html

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