Straightforward but slow Java solution


  • 2
    K
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> result = new ArrayList<>();
            int len = nums.length;
            int start = 0;
            int end = start;
            for(int i = 0; i < len; i++){
                if(i < len-1 && nums[i+1] == nums[i] + 1) end++;
                else{
                    if(start != end) {
                        String s = String.valueOf(nums[start]) + "->" + String.valueOf(nums[end]);
                        result.add(s);
                    }
                    else if (start == end){
                        String s = String.valueOf(nums[start]);
                        result.add(s);
                    }
                    start = i + 1;
                    end = start;
                }
            }
            return result;
        }
    }

Log in to reply
 

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