标签:
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.
因为是排序好的数组,所以只需每次向前扫描查找下一个数即可。
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int j = 0;
while (i + j + 1 < nums.length && nums[i + j] == nums[i + j + 1] - 1) {
j++;
}
if (j == 0) {
result.add("" + nums[i]);
} else {
result.add(nums[i] + "->" + nums[i + j]);
}
i += j;
}
return result;
}
}
标签:
原文地址:http://www.cnblogs.com/shini/p/4603600.html