228. Summary Ranges leetCode[Java]

来源:互联网 发布:互联网公司 薪资 知乎 编辑:程序博客网 时间:2024/05/16 23:48

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