LeetCode.228 Summary Ranges

来源:互联网 发布:大数据上市公司有几家 编辑:程序博客网 时间:2024/06/16 23:25

题目:

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input: [0,1,2,4,5,7]Output: ["0->2","4->5","7"]

Example 2:

Input: [0,2,3,4,6,8,9]Output: ["0","2->4","6","8->9"]

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

分析:

class Solution {    public List<String> summaryRanges(int[] nums) {        //给定排好序的数组,其中连续的元素放在一组,非连续的单独存放,返回结果        //思路:对于每个元素和前一个元素进行匹配        //注意:最后需要对最后单个元素或者元素对进行判断        List<String> list=new ArrayList<>();        if(nums.length==0||nums==null) return list;                int count=1;        int temp=nums[0];        int start=nums[0];        for(int i=1;i<nums.length;i++){            if(nums[i]==temp+1){                //为连续的                temp=nums[i];                count++;            }else {                //不连续                if(count==1){                    //只有一个元素                    list.add(String.valueOf(start));                }else if(count>1){                    //有多个元素                    String str=String.valueOf(start)+"->"+String.valueOf(temp);                    list.add(str);                    //更新start和temp                                    }                start=nums[i];                temp=nums[i];                count=1;            }        }                //防止:对最后的元素进行处理        if(count>1){            //说明还有元素对            String str=String.valueOf(start)+"->"+String.valueOf(temp);            list.add(str);        }else if(count==1){            //最后只有单个元素            list.add(String.valueOf(start));        }                return list;    }}


原创粉丝点击