Skip to content

228. Summary Ranges

Jacky Zhang edited this page Sep 12, 2016 · 1 revision

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

解题思路为顺序扫描数组,记住range的index,然后分情况处理string。

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