题目要求
解法一:
可以通过sort的方式,简单找出最长的连续的序列。但是本题不可sort。因此为了查找高效,采用hashMap来存已知数字,别对数字是否被用过进行标记,分别向前和向后找出存在的连续序列。
Time: O(n) Space: O(n)
代码1:
import java.util.*;
class Program {
public static int[] largestRange(int[] array) {
// Write your code here.
if (array == null || array.length == 0) return new int[]{};
HashMap<Integer, Boolean> map = new HashMap<>();
int[] res = new int[2];
int[] temp = new int[2];
for (int num : array) {
map.put(num, true);
}
for (int i = 0; i < array.length; i++) {
if (map.get(array[i])) {
map.put(array[i], false);
int num = array[i] - 1;
temp[0] = array[i];
temp[1] = array[i];
while (map.containsKey(num)) {
map.put(num, false);
temp[0] = num;
num--;
}
num = array[i] + 1;
while (map.containsKey(num)) {
map.put(num, false);
temp[1] = num;
num++;
}
if ((temp[1] - temp[0]) >= (res[1] - res[0])) {
System.arraycopy(temp, 0, res, 0, 2);
}
}
}
return res;
}
}
代码2(写法简化):
import java.util.*;
class Program {
public static int[] largestRange(int[] array) {
// Write your code here.
if (array == null || array.length == 0) return new int[]{};
HashMap<Integer, Boolean> map = new HashMap<>();
int[] res = new int[2];
int longest = 0;
for (int num : array) {
map.put(num, true);
}
for (int num : array) {
if (map.get(num)) {
map.put(num, false);
int left = num - 1;
int right = num + 1;
int tempLongth = 1;
while (map.containsKey(left)) {
map.put(left, false);
tempLongth++;
left--;
}
while (map.containsKey(right)) {
map.put(right, false);
tempLongth++;
right++;
}
if (tempLongth > longest) {
longest = tempLongth;
res = new int[]{left + 1, right - 1};
}
}
}
return res;
}
}