Java十大算法(五)——贪心算法之集合覆盖

算法描述

贪心算法就是每一次都给我们的问题找一个靠近问题的最优解,个人理解贪心算法解题的核心点在于如何描述最优解?在我们逐步求解的过程中最优解是如何确定的。下面我们用一个贪心算法比较经典的案例来说明:

贪心算法求得这个解未必是最优解

 这里的最优解我们可以描述为,可以包含最多有效城市的集合,在算第一个集合的时候肯定是那个集合size最大就先选那个集合,选第二个集合的时候有效城市集合就是总的城市集合中除去第一个已选集合中包含的城市剩下的城市集合。

代码分析

代码实现

public class GreedyAlgorithm {

    public static void main(String[] args) {

        HashMap<String, HashSet<String>> dataGather = new HashMap<>();

        HashSet<String> hashSet1 = new HashSet();
        HashSet<String> hashSet2 = new HashSet();
        HashSet<String> hashSet3 = new HashSet();
        HashSet<String> hashSet4 = new HashSet();
        HashSet<String> hashSet5 = new HashSet();

        hashSet1.add("北京");
        hashSet1.add("上海");
        hashSet1.add("天津");
        hashSet2.add("广州");
        hashSet2.add("北京");
        hashSet2.add("深圳");
        hashSet3.add("成都");
        hashSet3.add("上海");
        hashSet3.add("杭州");
        hashSet4.add("上海");
        hashSet4.add("天津");
        hashSet5.add("杭州");
        hashSet5.add("大连");

        dataGather.put("key1",hashSet1);
        dataGather.put("key2",hashSet2);
        dataGather.put("key3",hashSet3);
        dataGather.put("key4",hashSet4);
        dataGather.put("key5",hashSet5);

        handleMeath(dataGather);

    }

    public static void handleMeath(HashMap<String,HashSet<String>> dataGather){
        HashSet<String> allDiffData = new HashSet<>();
        for(HashSet entity: dataGather.values()){
            allDiffData.addAll(entity);
        }

        System.out.println(allDiffData.toString());

        ArrayList<String> keyLists = new ArrayList<>();
        int count = 0;
        int countMax = 0;
        String maxFlag = "";
        while (allDiffData.size()>0){
            maxFlag ="";
            countMax =0;
            for (Map.Entry<String,HashSet<String>> entity : dataGather.entrySet()) {
                count =0;
                for (String stringTemp : entity.getValue()){
                    if(allDiffData.contains(stringTemp)){
                        count++;
                    }
                }

                if(count>countMax){
                    countMax = count;
                    maxFlag = entity.getKey();
                }
            }
            keyLists.add(maxFlag);
            allDiffData.removeAll(dataGather.remove(maxFlag));
        }
        System.out.println(keyLists.toString());

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值