您可以创建一个
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<Integer> indexList = Arrays.asList(23,32,43,45,47,56,49,47); // get this from database List<Integer> valueList = Arrays.asList(20,20,18,24,10,6,2,12); // get this from database List<Pair> pairList = new ArrayList<>(); for(int i = 0; i < indexList.size();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 < pairList.size(); i++){ Pair p = pairList.get(i); if(sum == 0){ min = p.key; max = p.key; } sum += p.value; if(sum < LIMIT){ max = p.key; } else { if(sum > LIMIT){ i--; } else { max = p.key; } System.out.println(min+"_"+max); sum = 0; } }}哪些打印:
23_3243_4345_56
我将向您展示如何通过地图创建一个配对列表(使用a
linkedHashMap来保留插入顺序)(显然,您需要对
Pair类进行一些修改):
Map<Long, Integer> m = new linkedHashMap<>();//fill your map hereList<Pair> l = new ArrayList<>();for(Map.Entry<Long, Integer> entries : m.entrySet()){ l.add(new Pair(entries.getKey(), entries.getValue()));}//Now you have a list of Pair


