Problem:
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"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
https://leetcode.com/problems/summary-ranges/
Java Code:
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<String>();
if (nums == null || nums.length == 0) {
return result;
}
int pre = nums[0];
int range = 0;
for (int i = 1; i <= nums.length; i++) {
if (i != nums.length && nums[i - 1] == nums[i] - 1) {
range++;
} else {
if (range == 0) {
result.add(Integer.toString(pre));
} else {
result.add(Integer.toString(pre) + "->" + Integer.toString(pre + range));
}
if (i != nums.length) {
pre = nums[i];
range = 0;
}
}
}
return result;
}
}
没有评论:
发表评论