Prompt
Write a function that takes in an array of integers and returns an array of length 2 representing the largest range of integers contained in that array.
The first number in the output array should be the first number in the range, while the second number should be the last number in the range.
A range of numbers is defined as a set of numbers that come right after each other in the set of real integers. For instance, the output array [2, 6] represents the range {2, 3, 4, 5, 6}, which is a range of length 5. Note that numbers don’t need to be sorted or adjacent in the input array in order to form a range.
You can assume that there will only be one largest range.
Sample Input
array = [1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6]
Sample Output
[0, 7]
Solution
import java.util.*;
class Program {
//O(n) time | O(n) space
public static int[] largestRange(int[] array) {
// Write your code here.
int[] bestRange = new int[2];//C
int longestLength = 0;
Map<Integer, Boolean> nums = new HashMap<Integer, Boolean>();
for (int num : array) {//A
nums.put(num, true);
}
for (int num : array){ //B
if (!nums.get(num)) continue;
nums.put(num, false);
int currentLength = 1;
int left = num - 1;
int right = num + 1;
while (nums.containsKey(left)) {
nums.put(left, false);
currentLength += 1;
left -= 1;
}
while (nums.containsKey(right)) {
nums.put(right, false);
currentLength += 1;
right += 1;
}
if (currentLength > longestLength) {
longestLength = currentLength;
bestRange = new int[] {left + 1, right - 1};
}
}
return bestRange;
}
}
How to Bug Free
注意输入法,敲代码的时候,如果中途有中文跳出来,submit前要检查
要去了解体会总结不同数据结构的应用场景
Why can’t I Solve this
Conclusion
# A
- 记住hashtable的用法及method
# B
这里处理的值,并不是序号
#C
int [] bestRange = new int[2];
int longestLength = 0;
int currentLength = 1;
这种纪录储存数据的思想很常见