# Arrays分类算法-Largest Range

#### 题目要求

Time: O(n) Space: O(n)

import java.util.*;

class Program {
public static int[] largestRange(int[] array) {
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;
}
}


import java.util.*;

class Program {
public static int[] largestRange(int[] array) {
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;
}
}

• 点赞
• 评论 1
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

This is 李若若的老公

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

05-15 814

10-29 114
01-12 9566
05-23 2455
05-12 225
09-13 58
07-16 1966
02-25 369
12-16 263
04-09 5811