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

Summary Ranges

时间:2015-09-12 17:36:12      阅读:123      评论: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"].

Java代码如下:

public class Solution {

    private List<String> sR = new ArrayList<String>();
    private StringBuilder sb = new StringBuilder();
    private boolean flag = false;
    private int start, tmp;
    
    public List<String> summaryRanges(int[] nums) {
        if (nums.length == 0) {
            return sR;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i == 0) {
                start = nums[i];
                tmp = nums[i];
                continue;
            }
            if (nums[i] - tmp == 1) {
                tmp = nums[i];
                flag = true;
                continue;
            } else if (flag) {
                sb.delete(0, sb.length());
                sb.append(start + "->" + tmp);
                sR.add(sb.toString());
                flag = false;
            } else {
                sR.add(Integer.toString(tmp));
            }
            start = nums[i];
            tmp = nums[i];
        }
        if (flag) {
            sb.delete(0, sb.length());
            sb.append(start + "->" + nums[nums.length - 1]);
            sR.add(sb.toString());
        } else {
            sR.add(Integer.toString(nums[nums.length - 1]));
        }
        return sR;
    }
}

 

Summary Ranges

标签:

原文地址:http://www.cnblogs.com/lasclocker/p/4803255.html

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