分享

228. Summary Ranges C#

 雪柳花明 2016-12-21

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

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

Subscribe to see which companies asked this question






public class Solution {
    public IList<string> SummaryRanges(int[] nums) {
        if(nums==null)
        {
            return null;
        }
        if(nums.Length<=0)
        {
            return new List<string>();
        }
        List<string> list=new List<string>();
        if(nums.Length==1)
        {
            list.Add(nums[nums.Length-1]+"");
            return list;
        }
        
        int start=nums[0];
        int end=nums[0];
        for(int i=1;i<nums.Length;i++)
        {
            //如果两个数相连,将end往后移动
            if(nums[i]-nums[i-1]==1)
            {
                end=nums[i];
            }
            else
            {
                if(start!=end)
                {
                    list.Add(""+start+"->"+end);
                }
                start=nums[i];
                end=nums[i];
            }
            if(i==nums.Length-1)
            {
                if(start==end)
                {
                    list.Add(""+start);
                }
                else
                {
                    list.Add(""+start+"->"+end);
                }
            }
        }
        
        return list;
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多