LeetCode 228 汇总区间 java

力扣228 题目

        题目链接

        228. 汇总区间 - 力扣(LeetCode)        

        题目描述

        

        

 基本思路

        使用HashMap进行键的比较,值的赋值,键用来记录区间的开始位置,值用来记录区间长度,然后将结果加入ArrayList。

代码

class Solution {
    public List<String> summaryRanges(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        List<String> s = new ArrayList<>();
        int j = 1;//用来记录和起始位置的距离方便下一个连续元素进行判断
        int w = 0;//用来在判断条件不成立时将上一个元素加入List
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i] - j)) {
                map.put(nums[i] - j, map.get(nums[i] - j) + 1);
                j++;
            } else {
                if (map.get(w) != null) {
                    if (map.get(w) == 0) {
                        int t = w;
                        s.add("" + t);
                    } else {
                        int q = w;
                        int t = map.get(w) + w;
                        s.add(q + "->" + t);
                    }
                }
                map.put(nums[i], 0);
                w = nums[i];//记录下一个加入List的元素
                j = 1;
            }
        }
        if (map.get(w) != null) {//判断map中的最后一个元素
                    if (map.get(w) == 0) {
                        int t = w;
                        s.add("" + t);
                    } else {
                        int q = w;
                        int t = map.get(w) + w;
                        s.add(q + "->" + t);
                    }
                }
        return s;
    }
}

 运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值