Accepted JAVA code


  • 0
    S
        public List<String> summaryRanges(int[] nums) {
            List<String> list = new ArrayList<String>();
            if(nums.length == 0)
                return list;
            if(nums.length == 1) {
                list.add(Integer.toString(nums[0]));
                return list;
            }
            StringBuilder builder = new StringBuilder();
            builder.append(Integer.toString(nums[0]));
            int i = 1;
            int ini_i = 0;
            while(i < nums.length) {
                if(nums[i] - nums[i-1] == 1)
                {
                    i++;
                    continue;
                }
                else {
                    if((i-1) == ini_i)
                    {
                        list.add(builder.toString());
                    }
                    else {
                        builder = builder.append("->");
                        builder = builder.append(Integer.toString(nums[i-1]));
                        list.add(builder.toString());
                    }
                    ini_i = i;
                    builder = new StringBuilder(Integer.toString(nums[i]));
                    i++;
                }
            }
            if(nums[nums.length - 1] - nums[nums.length - 2] == 1)
            {
                builder = builder.append("->");
                builder = builder.append(Integer.toString(nums[nums.length-1]));
                list.add(builder.toString());
            }
            else
                list.add(builder.toString());
            
            return list;
        }
    }

Log in to reply
 

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