LeetCode:228. 汇总区间[Java实现]

给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。

示例 1:

输入: [0,1,2,4,5,7]
输出: [“0->2”,”4->5”,”7”]
解释: 0,1,2 可组成一个连续的区间; 4,5 可组成一个连续的区间。
示例 2:

输入: [0,2,3,4,6,8,9]
输出: [“0”,”2->4”,”6”,”8->9”]
解释: 2,3,4 可组成一个连续的区间; 8,9 可组成一个连续的区间。

滑水题

class Solution {
   public List<String> summaryRanges(int[] nums) {
        List<String> list = new ArrayList<>();
        int pos = 0;
        while (pos < nums.length) {
            StringBuilder it = new StringBuilder(""+nums[pos]);
            int temp = pos;
            while (pos + 1 < nums.length && nums[pos + 1] == nums[pos] + 1)
                pos++;

            if (pos != temp)
                it.append("->").append(nums[pos]);
            list.add(it.toString());
            pos++;
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35170267/article/details/81234996