Summary Ranges
Problem:
Analysis:
Still, overflow problem. Use index instead of actual value solves overflow issue.
Solution:
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"]
Analysis:
Still, overflow problem. Use index instead of actual value solves overflow issue.
Solution:
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> summary = new ArrayList<>();
for (int i = 0, j = 0; j < nums.length; ++j) {
// check if j + 1 extends the range [nums[i], nums[j]]
if (j + 1 < nums.length && nums[j + 1] == nums[j] + 1)
continue;
// put the range [nums[i], nums[j]] into the list
if (i == j)
summary.add(nums[i] + "");
else
summary.add(nums[i] + "->" + nums[j]);
i = j + 1;
}
return summary;
}
}
评论
发表评论