作者:浅蓝色shenjinjin | 来源:互联网 | 2023-10-09 20:31
您可以创建一个Pair
包含键和值的类,而不是使用Map 。
class Pair {
public int key;
public int value;
public Pair(int key, int value){
this.key = key;
this.value = value;
}
}
然后创建一个配对列表并对其进行迭代。如果总和为0,则初始化最小值和最大值。然后对于每个迭代的对,将其值加到总和上。如果总和小于,请继续循环并更新max键,否则可能出现两种情况:
- 总和等于限制,因此请更新最大密钥
- 总和不等于限制(因此更好),减少索引并且不更新最大密钥
public static void main(String[] arg) {
List indexList = Arrays.asList(23,32,43,45,47,56,49,47); // get this from database
List valueList = Arrays.asList(20,20,18,24,10,6,2,12); // get this from database
List pairList = new ArrayList<>();
for(int i = 0; i pairList.add(new Pair(indexList.get(i), valueList.get(i)));
}
int sum = 0;
int min = -1;
int max = -1;
for(int i = 0; i Pair p = pairList.get(i);
if(sum == 0){
min = p.key;
max = p.key;
}
sum += p.value;
if(sum max = p.key;
} else {
if(sum > LIMIT){
i--;
} else {
max = p.key;
}
System.out.println(min+"_"+max);
sum = 0;
}
}
}
哪些打印:
23_32
43_43
45_56
我将向您展示如何通过地图创建一个配对列表(使用a LinkedHashMap
来保留插入顺序)(显然,您需要对Pair
类进行一些修改):
Map m = new LinkedHashMap<>();
//fill your map here
List l = new ArrayList<>();
for(Map.Entry entries : m.entryset()){
l.add(new Pair(entries.getKey(), entries.getvalue()));
}
//Now you have a list of Pair