228. Summary Ranges leetCode[Java]

228. Summary Ranges

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

问题描述:本文是给出非重复的nums[int]数组,然后需要根据给出的数组结构,返回List<String>的list元素,

分析上面给出的样例可以知道,返回的List是将数组内的连续不重复的0~2,4~5,以及单独的7作为返回元素,所以

我们可以通过遍历一遍数组,然后判断连续两个元素是否是互邻的自然数,来决定其list归属,遍历一遍数组,可

得到全部的结果。


public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> list = new ArrayList<String>();
        
        if(nums.length == 0)
            return list;
        int i = 1;
        int pre = nums[0];  //记录连续的nums元素的最开始数值
        int next = nums[0]; //记录连续的nums元素的最末尾数值
        
        while(i < nums.length){
            if(nums[i]-nums[i-1] == 1){
                next = nums[i];
                i++;
            }else{
                if(pre == next){  //当连续的数只有一个的时候,只需要输出"nums[i]"
                    list.add(pre+"");
                }else{
                    list.add(pre+"->"+next+""); //当连续的数有多个的时候,输出"pre->next"
                }
                
                pre = nums[i];
                next = nums[i];
                i++;
            }
        }
        if(pre == next){  //输出最后一个list元素
            list.add(pre+"");
        }else{
            list.add(pre+"->"+next+"");
        }
        return list;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值