Java - Intuitive and commented solution that is rather slow


  • 0
    T
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            
            List<String> ret = new ArrayList<String>();
            int start = 0, mid = 0;
            for(int i = 0; i < nums.length; i++) {
                if(i == 0) {
                    start = mid = nums[0];
                } 
                //if the next index is valid AND is one greater than the current mid value
                if(i < nums.length-1 && nums[i+1] == mid + 1) {
                    mid = nums[i+1];
                } else {
                    //we're either at the end of the array, or a chain was broken - let's
                    //add the string and start our chain over
                    if(start == mid) {
                        ret.add(Integer.toString(start));
                    } else {
                        ret.add(start + "->" + mid);
                    }
                    
                    if(i < nums.length-1) {
                        start = nums[i+1];
                    } 
                    mid = start;
                }
            }
            return ret;
        }
    }

Log in to reply
 

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