【发布时间】:2011-07-21 21:07:43
【问题描述】:
给你一个整数数组。您必须输出最大范围,以便该范围内的所有数字都存在于数组中。这些数字可能以任何顺序出现。例如,假设数组是
{2, 10, 3, 12, 5, 4, 11, 8, 7, 6, 15}
这里我们找到两个(非平凡的)范围,这些范围中的所有整数都存在于数组中,即 [2,8] 和 [10,12]。其中 [2,8] 是较长的一个。所以我们需要输出它。
当我被问到这个问题时,我被要求在线性时间内完成此任务,并且不使用任何排序。我以为可能有一个基于哈希的解决方案,但我想不出什么。
这是我的解决方案尝试:
void printRange(int arr[])
{
int n=sizeof(arr)/sizeof(int);
int size=2;
int tempans[2];
int answer[2];// the range is stored in another array
for(int i =0;i<n;i++)
{
if(arr[0]<arr[1])
{
answer[0]=arr[0];
answer[1]=arr[1];
}
if(arr[1]<arr[0])
{
answer[0]=arr[1];
answer[1]=arr[0];
}
if(arr[i] < answer[1])
size += 1;
else if(arr[i]>answer[1]) {
initialize tempans to new range;
size2=2;
}
else {
initialize tempans to new range
}
}
//I have to check when the count becomes equal to the diff of the range
我被困在这部分...我不知道应该使用多少个 tempanswer[] 数组。
【问题讨论】:
-
这个问题的措辞有点混乱,虽然我现在明白了。您想在数组中找到最大的一组连续数字。在您的示例中,
2, 3, 4, 5, 6, 7, and 8是数组中的值,但1 and 9不是,因此您的候选结果之一是[2 - 8]。
标签: arrays algorithm time-complexity space-complexity