Easy to understand Java solution


  • 0
    T
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
        
            List<String> result = new LinkedList<>();
        
            int start = 0, i = 1;
            while (start < nums.length) {
                
                // increase until end of range 
                while (i < nums.length && nums[i] == nums[i-1]+1) i++; 
                result.add(summaryRange(nums[start], nums[i-1]));
                start = i++;
            }
            
            return result;
        }
        
        private String summaryRange(int from, int to) {
            
            if (from == to) return "" + from;
            
            String result = "";
            result += from;
            result += "->";
            result += to;
            
            return result;
            
        }
    }
    

Log in to reply
 

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