Summary Ranges

题目链接:https://leetcode.com/problems...

loop两种写法:

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList();
        if(nums.length == 0) return result;
        /* loop invariant: nums[i] != nums[i-1] + 1 
         */
        for(int i = 0; i < nums.length; i++) {
            int prev = nums[i];
            while(i < nums.length - 1 && nums[i] + 1 == nums[i+1]) {
                i++;
            }
            result.add(getRange(prev, nums[i]));
        }
        return result;
    }
    
    private String getRange(int i, int j) {
        if(i == j) return "" + i;
        return i + "->" + j;
    }
}
public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList();
        if(nums.length == 0) return result;
        
        int prev = nums[0];
        for(int i = 0; i < nums.length; i++) {
            if(i == nums.length - 1 || nums[i] + 1 != nums[i+1]) {
                result.add(getRange(prev, nums[i]));
                if(i != nums.length - 1) prev = nums[i+1];
            }
        }
        return result;
    }
    
    private String getRange(int i, int j) {
        if(i == j) return "" + i;
        return i + "->" + j;
    }
}

lulouch13
13 声望6 粉丝

« 上一篇
Word Abbreviation
下一篇 »
Decode String