LeetCode 228. Summary Ranges(java)

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]

Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
思路:归纳假设,为G问题,最后merge到F问题即可,和LC38题的思路相同。
public List<String> summaryRanges(int[] nums) {
        //special case 
        List<String> res = new ArrayList<>();
        if (nums.length == 0) return res;
        //base case
        int start = nums[0];
        //general case
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i - 1] + 1) {
                group(res, start, nums[i - 1]);
                start = nums[i];
            }
        }
        group(res, start, nums[nums.length - 1]);
        return res;
    }
    public void group(List<String> res, int start, int end) {
        StringBuilder sb = new StringBuilder();
        if (start == end) {
            sb.append(start);
        } else {
            sb.append(start);
            sb.append("->");
            sb.append(end);
        }
        res.add(sb.toString());
    }
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页