我有一张java地图:
Map<String, ArrayList<Integer>> positions = new HashMap<String, ArrayList<Integer>>();
这张地图基本上包含:
word1: 2 10 17
word2: 3 8 15 20
word3: 6 9 19 22
word4: 7 12 18 24
..... and so on
现在我想找到所有单词位置之间的最小范围。我们将有唯一的和排序的位置(即没有两个整数将是相同的)。
The minimum range here is 3 (between 10, 8, 9 and 7)
我们应该如何处理这个问题?
I thought of the following steps:
1) Have pointers as many as words length.
2) In this example, we have 4 pointers, pointing towards 2, 3, 6 and 7.
3) The range is calculated which comes out be 5.
4) Keep this range in a certain variable say 'min'.
5) Repeat until all positions in all lists have not been read:
a) Move the lowest pointer to the next in the list(In this example, we move pointer-1 to point to 10).
b) Calculate the range again (this comes to be 7 now).
c) If the new range < min:
min = new range
6) Return 'min'
但我不知道如何用Java来解决这个问题。有人可以帮帮我吗?如果你有某种不同的方法,我会欢迎它。
答案 0 :(得分:0)
这是我提出的解决方案(用C#编写,但基本的想法应该转移到Java)
public class RangeFinder
{
public List<List<int>> WordList { get; set; }
public List<int> IndexList { get; private set; }
public int MinRange()
{
IndexList = new List<int>();
for (int i = 0; i < WordList.Count; i++)
{
IndexList.Add(0);
}
int min = Int32.MaxValue;
do
{
var range = CalculateRange();
if (range < min)
{
min = range;
}
}
while (!EndReached());
return min;
}
private int CalculateRange()
{
var maxVal = Int32.MinValue;
var minVal = Int32.MaxValue;
for (int i = 0; i < WordList.Count; i++)
{
var word = WordList[i];
var val = word[IndexList[i]];
if(val > maxVal)
{
maxVal = val;
}
if(val < minVal)
{
minVal = val;
}
}
return maxVal - minVal;
}
private bool EndReached()
{
for(int i=0; i < IndexList.Count; i++)
{
var word = WordList[i];
var wordCount = word.Count;
IndexList[i] = (++IndexList[i]) % wordCount;
if(IndexList[i] > 0)
{
return false;
}
}
return true;
}
}
简要概述其工作原理: 在创建类时,将填充WordList(对于Java,创建一个填充WordList的构造函数)。在我的测试代码中,我刚为每个单词创建了一个List,并列出了每个单词的列表。 IndexList跟踪我们用每个单词查看的数字。它们都从索引0开始。然后,我们递增第一个单词。当第一个单词的索引换行时,我们递增第二个单词。当第二个单词的索引换行时,我们递增第三个单词。这一直持续到最后一个单词的索引换行。当发生这种情况时,我们知道所有可能的组合已被查看,我们可以返回最小范围。