最近做算法,有一道算法题是这样的
搜索最长的连续串,比如给定的数组是 1, 3, 6, 4, 8, 4, 87, 101, 5,那么返回的结果是 1 3->6 8 87 101。
这道题看似很简单,其实暗藏玄机。具体思路是:先做排序,然后再遍历数组找结果。写代码时要注意很多细节。
public static void main(String []args) {
int[] arr = {1, 3, 6, 4, 8, 4, 87, 101, 5};
Arrays.sort(arr);
ArrayList<String> ret = new ArrayList();
int start = Integer.MIN_VALUE;
int end = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (i > 0 && arr[i] == arr[i - 1]) {
continue;
} else if (start == Integer.MIN_VALUE) {
start = arr[i];
} else if (arr[i] == arr[i - 1] + 1) {
end = arr[i];
} else {
if (end == Integer.MIN_VALUE) {
ret.add("" + start);
} else {
ret.add(start + "->" + end);
}
start = arr[i];
end = Integer.MIN_VALUE;
}
}
if (end == Integer.MIN_VALUE) {
ret.add("" + start);
} else {
ret.add(start + "->" + end);
}
for (String str : ret) {
System.out.print(str + " ");
}
// 执行结果: 1 3->6 8 87 101
}