栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

根据特定条件分割地图

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

根据特定条件分割地图

您可以创建一个

Pair
包含键和值的类,而不是使用Map 。

class Pair {    public int key;    public int value;    public Pair(int key, int value){        this.key = key;        this.value = value;    }}

然后创建一个配对列表并对其进行迭代。如果总和为0,则初始化最小值和最大值。然后对于每个迭代的对,将其值加到总和上。如果总和小于,请继续循环并更新max键,否则可能出现两种情况:

  1. 总和等于限制,因此请更新最大密钥
  2. 总和不等于限制(因此更好),减少索引并且不更新最大密钥

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483591.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号