leetcode228. 汇总区间

67 篇文章 0 订阅

题目

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

示例 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 可组成一个连续的区间。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/summary-ranges

解题思路

使用双指针,判断nums[next] - nums[pre] == next-pre即可。

代码如下

class Solution {
    public List<String> summaryRanges(int[] nums) {
        if (nums.length < 1) {
            return new ArrayList<>();
        }
        List<String> res = new ArrayList<>();
        if (nums.length < 2) {
            res.add(String.valueOf(nums[0]));
            return res;
        }
        int pre = 0, next = 1;
        while (pre < nums.length) {
            while (next < nums.length && nums[next] - nums[pre] == next-pre) {
                next++;
            }
            if (next - 1 != pre) {
                res.add(nums[pre] + "->" + nums[next-1]);
            } else {
                res.add(String.valueOf(nums[pre]));
            }
            pre = next;
        }
        return res;
    }
}

提交结果

> 这里是引用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值