算法描述
贪心算法就是每一次都给我们的问题找一个靠近问题的最优解,个人理解贪心算法解题的核心点在于如何描述最优解?在我们逐步求解的过程中最优解是如何确定的。下面我们用一个贪心算法比较经典的案例来说明:
贪心算法求得这个解未必是最优解
这里的最优解我们可以描述为,可以包含最多有效城市的集合,在算第一个集合的时候肯定是那个集合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());
}
}