Wednesday, July 1, 2015

228. Summary Ranges Add to List QuestionEditorial Solution

Q:
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
A:
就是挨个数呗
------------一点小技巧就是每次遇到一个数字的时候,决定前面的。  这样,就需要在for 循环之后再查看一遍----------

public class Solution {
        List<String> res = new LinkedList();
        for(int i =0;i < nums.length ; i++){
            int start = nums[i];
            String str = ""+start;
            while(   i+1< nums.length   && nums[i+1] == nums[i]+1)
                i++;
            if(start != nums[i])
                str += "->"+nums[i];
            res.add(str);
        }
        return res;   
    }
}

--------思路同上,  但是用了递归——————————

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new LinkedList<>();
        helper(nums, res, 0);
        return res;
    }
    public void helper(int[] nums, List<String> res, int i){
        int n = nums.length;
        if(i >= n)
            return;
        int start = nums[i];
        while(i+1<n && nums[i+1] == nums[i] + 1){
            i++;
        }
        int end  = nums[i];
        if(start == end)
            res.add("" + start);
        else
            res.add( "" + start + "->" + end);
        helper(nums,res, i+1);
    }
}
 



Mistakes:





No comments:

Post a Comment