My Java Solution


  • 0
    E
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String>res=new ArrayList<String>();
            if(nums.length==0){
                return res;
            }
            else if(nums.length==1){
                res.add(nums[0]+"");
                return res;
            }
            int start=nums[0],end=-1,flag=0;
            for(int i=0;i<nums.length-1;i++){
                if(nums[i]+1==nums[i+1]){
                    flag=1;
                    if(i+1==nums.length-1){
                    	end=nums[i+1];
                    	res.add(start+"->"+end);
                    	return res;
                    }
                    continue;
                }
                else{
                    end=nums[i];
                    if(flag==0 || start==end){
                        res.add(start+"");
                        start=nums[i+1];
                        continue;
                    }
                    res.add(start+"->"+end);
                    start=nums[i+1];
                }
            }
            if(start==nums[0]){
                res.add(start+"->"+nums[nums.length-1]);
            }
            if(nums[nums.length-1]!=nums[nums.length-2]+1){
            	res.add(nums[nums.length-1]+"");
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.