Java 0ms Solution -- easy to understand


  • 0
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> list = new ArrayList<>();
            if(nums == null || nums.length == 0) return list;
            
            //there is no need to use start and end variable, but they makes the code easier to read
            int start = 0;
            int end = 0;
            StringBuilder sb = new StringBuilder();
    
            //the range is [start, end]
            for(int i = 0; i < nums.length ; i++){
                //start
                if( i == 0 || nums[i-1] + 1 != nums[i]) {
                    start = i;
                    sb = new StringBuilder();
                    sb.append(nums[start]);
                }
                //end
                if( i == nums.length - 1 || nums[i] + 1 != nums[i+1]){
                    end = i;
                    if(end != start){
                        sb.append("->").append(nums[end]);
                    }
                    list.add(sb.toString());
                }
            }
            return list;
        }
    }
    

Log in to reply
 

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