Sunday, September 13, 2015

Summary Ranges

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"].
Solution1: time complexity is O(n), space complexity is O(n).
记录两个值 lowBound=nums[i], highBound=nums[i].  如果nums[i+1]  - highBound == 1, 则i++,highBound=nums[i], 继续比较。否则, 插入字符串 lowBound->highBound.
public class Solution {
    public ArrayList summaryRanges(int[] nums) {
        ArrayList res = new ArrayList();
        if (nums == null || nums.length == 0) {
            return res;
        }
        
        for (int i = 0; i < nums.length; i++) {
            int lowBound = nums[i];
            int highBound = nums[i];
            while (i < nums.length - 1 && nums[i + 1] - highBound == 1) {
                i++;
                highBound = nums[i];
            }
            
            StringBuilder s = new StringBuilder();
            s.append(lowBound);
            if (lowBound == highBound) {
                res.add(s.toString());
            } else {
                s.append("->");
                s.append(nums[i]);
                res.add(s.toString());
            }
        }
        return res;
    }
}

No comments:

Post a Comment