My Solution, don't use "while" in for loop


  • 0
    Y
    class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> list = new ArrayList<>();
            
            if(nums == null || nums.length == 0) return list;
            
            int old = 0, start = 0;
            for(int i = 0; i <= nums.length; i++) {
                
                if(i == nums.length || (i != 0 && nums[i] - old != 1 )) {
                    String str = (start == i-1) ? ("") : ("->" + nums[i-1]);
                    list.add(nums[start] + str );
                    start = i;
                }
                
                if(i != nums.length) old = nums[i];
            }
            
            return list;
        }
    }
    
    

Log in to reply
 

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