Straightforward Java solution, two pointers


  • 0
    H
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> res = new ArrayList<>();
            if(nums==null||nums.length==0) return res;
            int start = 0;
            for(int i=0;i<nums.length-1;i++){
                if(nums[i+1]!=nums[i]+1){
                    res.add(getRange(nums, start, i));
                    start = i+1;
                }
            }
            res.add(getRange(nums, start, nums.length-1));
            
            return res;
        }
        
        private String getRange(int[] nums, int i, int j){
            if(i==j) return Integer.toString(nums[i]);
            else return nums[i] + "->" + nums[j];
        }
    }
    

Log in to reply
 

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