Summary Ranges

来源:互联网 发布:网络存储器怎么用 编辑:程序博客网 时间:2024/06/05 14:36

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.

Show Tags
Show Similar Problems

Have you met this question in a real interview?

silu: Pay more attention to the corner case.

public class Solution {    public List<String> summaryRanges(int[] nums) {        List<String> ret = new ArrayList<String>();        int len = nums.length;        if(len < 1)            return ret;        StringBuilder buffer = new StringBuilder();        for(int i = 0; i < nums.length; i++){            buffer.append(nums[i]);            if(i < len - 1 && nums[i] + 1 == nums[i + 1]){                buffer.append("->");                while(i < len - 1 && nums[i] + 1 == nums[i + 1]){                    i++;                }                buffer.append(nums[i]);            }            ret.add(buffer.toString());            buffer = new StringBuilder();        }        return ret;    }}


0 0
原创粉丝点击