目录
定义:
又称贪婪算法是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,算法得到的是在某种意义上的局部最优解。
贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择。
原理:
①建立数学模型来描述问题。
③对每个子问题求解,得到子问题的局部最优解 [2] 。
④把子问题的解局部最优解合成原来解问题的一个解 [2] 。
贪心算法是一种对某些求最优解问题的更简单、更迅速的设计技术。贪心算法的特点是一步一步地进行,常以当前情况为基础根据某个优化测度作最优选择,而不考虑各种可能的整体情况,省去了为找最优解要穷尽所有可能而必须耗费的大量时间。
存在问题:
1、不能保证解是最佳的。因为贪心算法总是从局部出发,并没从整体考虑;
2、贪心算法一般用来解决求最大或最小解;
3、贪心算法只能确定某些问题的可行性范围。
示例:
图示:
代码:
package SF;
import java.util.*;
public class Txsf {
public static void main(String[] args) {
int[] A={10,24,8,32,98,55,76,20,3,33};
int[] B={13,25,25,11,87,64,77,21,6,39};
int num1=compare(A,B);
int[] ans=advantagecount(A,B);
System.out.println(Arrays.toString(advantagecount(A,B)));
int num2=compare(ans,B);
System.out.println("大小:"+A.length);
System.out.println("不做处理:"+num1);
System.out.println("贪心算法:"+num2);
}
//贪心算法
public static int[] advantagecount(int[] A,int[]B){
int[] sortB=B.clone();//克隆B
Arrays.sort(sortB);
Arrays.sort(A);//排序
Map<Integer, Deque<Integer>> bmap=new HashMap<>();//数据结构,Hashmap
//初始化数据结构
for (int b:B){
bmap.put(b,new LinkedList<>());
}
Deque<Integer> aq=new LinkedList<>();
//进行贪心算法
int j=0;
for (int a:A){
if (a>sortB[j]){
bmap.get(sortB[j++]).add(a);
}else {
aq.add(a);
}
}
//取出元素
int[] ans=new int[A.length];
for (int i = 0; i < B.length; i++) {
if (bmap.get(B[i]).size()>0){
ans[i]=bmap.get(B[i]).removeLast();//后进先出
}else {
ans[i]=aq.removeLast();
}
}
return ans;
}
//比较函数,得出对应位置A比B大的元素个数
public static int compare(int[]A,int[]B){
int count=0;
if (A.length!=B.length)return -1;
for (int i = 0; i < A.length; i++) {
if (A[i]>B[i])count++;
}
return count;
}
}
运行结果:
[24, 55, 33, 20, 10, 98, 3, 32, 8, 76]
大小:10
不做处理:2
贪心算法:8
进程已结束,退出代码0