Leetcode-228-Summary Ranges
程序员文章站
2022-06-03 11:20:52
...
Summary Ranges
来自 <https://leetcode.com/problems/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"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
题目解读:给定一个有序数组,数组中没有重复的元素,返回数组摘要。例如,数组元素为[0,1,2,4,5,7],返回["0->2","4->5","7"]。
解析:
首先记录第一个元素,然后查看后面的一个元素是否和前一个元素相差1,如果是,则继续向后查看并记录该数。如果不是,则形成一个“第一个元素->当前元素”的摘要。然后把下一个元素作为第一个元素,依次遍历整个数组。
Java代码:
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<String>();
int start = 0;
int end = 0;
for (int i=0; i<nums.length; i++) {
if((i+1) < nums.length) {
if((nums[i+1]==nums[i]) || (nums[i+1]==(nums[i]+1))) {
end++;
continue;
} else {
end = i;
}
} else {
end = i;
}
if(nums[start] == nums[end]) {
result.add(nums[start] + "");
} else {
result.add(nums[start] + "->" + nums[end]);
}
start = end+1;
end = end+1;
}
return result;
}
算法性能:
上一篇: Servlet如何处理请求
下一篇: LeetCode--75.颜色分类(C)