问题描述
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”].
意:找出排序数组(无重复数字)中的各个连续的范围
算法思想
基本思想如下,给定排序数组
N<a1,a2,a3,...,an>,ai<ai+1,0≤i≤n-1,
如果N为空或者没有任何数,直接返回空元素List
如果N不为空,如果ai+1≠ai+1,则ai一定为某个范围起点,ai+1一定为某个范围终止点。
特殊考虑
- 第一个元素一定是某个起点,最后一个元素一定是某个范围的终点。
- 如果起点和终点相同,不需要打印箭头
算法实现
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Solution {
public static List<String> summaryRanges(int[] nums) {
List<String> ranges = new ArrayList<String>();
if (nums != null&&nums.length!=0) {
int start = nums[0];
int end = start;
for (int i = 0; i < nums.length - 1; i++) {
if ((nums[i] + 1) != nums[i + 1]) {
end = nums[i];
if (start != end)
ranges.add(start + "->" + end);
else
ranges.add(start + "");
start = nums[i + 1];
}
}
if (start != nums[nums.length - 1])
ranges.add(start + "->" + nums[nums.length - 1]);
else
ranges.add(start + "");
}
return ranges;
}
public static void main(String[] args) {
int arr[] = {0,2,3,4,5,6,8,9,12,14};
List<String> ranges = summaryRanges(arr);
Iterator<String> it = ranges.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
算法时间
算法扫描一遍数组
T(n)=O(n)
演示结果
0
2->6
8->9
12
14
时间: 2024-08-09 14:48:45