Java 0ms(You are here! Your runtime beats 97.90% of java submissions.)


  • 1
    S
    public static List<String> summaryRanges(int[] nums) {
    
        if (nums == null || nums.length == 0) {
            return new ArrayList<>();
        }
    
        List<String> result = new ArrayList<>(nums.length);
    
        int count = 0;
        int start;
        int end = 0;
    
        start = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] - nums[i - 1] == 1) {
                end = nums[i];
                count++;
            } else {
                if (count == 0) {
                    result.add(String.valueOf(start));
                } else {
                    result.add(start + "->" + end);
                }
                count = 0;
                start = nums[i];
            }
        }
         // like-> [0,1,2,3]
        if (count == 0) {
            result.add(String.valueOf(start));
        } else {
            result.add(start + "->" + end);
        }
        return result;
    }

Log in to reply
 

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