I have a TreeMap and I want to compare its i
and i+1
value in it. How can I do that. I know that TreeMap is sorted based on its keys but I want to compare the values and can't use sorting as I will loose original form. I want something like this but in TreeMap-
我有一个TreeMap,我想比较它的i和i + 1值。我怎样才能做到这一点。我知道TreeMap是根据它的键进行排序的,但我想比较这些值,不能使用排序,因为我会松散原始形式。我希望这样的东西,但在TreeMap-
int a[] = new int[n];
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1])
{
c++;
}
}
1 个解决方案
#1
3
Well you can do it like that:
那么你可以这样做:
TreeMap<Integer,Integer> tree=new TreeMap<>();
tree.put(1,5);
tree.put(2,6);
tree.put(3,4);
tree.put(4,4);
Entry<Integer,Integer> entry=tree.firstEntry();
int c=0;
while(tree.higherEntry(entry.getKey())!=null) {
if(entry.getValue()>tree.higherEntry(entry.getKey()).getValue())
c++;
entry=tree.higherEntry(entry.getKey());
}
Using the higherEntry, higherKey etc.
使用higherEntry,higherKey等。
By the way in your example you will get an ArrayIndexOutOFBound I think because of a[i + 1]
在你的例子中,你会得到一个ArrayIndexOutOFBound我认为因为[i + 1]
#1
3
Well you can do it like that:
那么你可以这样做:
TreeMap<Integer,Integer> tree=new TreeMap<>();
tree.put(1,5);
tree.put(2,6);
tree.put(3,4);
tree.put(4,4);
Entry<Integer,Integer> entry=tree.firstEntry();
int c=0;
while(tree.higherEntry(entry.getKey())!=null) {
if(entry.getValue()>tree.higherEntry(entry.getKey()).getValue())
c++;
entry=tree.higherEntry(entry.getKey());
}
Using the higherEntry, higherKey etc.
使用higherEntry,higherKey等。
By the way in your example you will get an ArrayIndexOutOFBound I think because of a[i + 1]
在你的例子中,你会得到一个ArrayIndexOutOFBound我认为因为[i + 1]