貪心演算法的相關題目(Java實現)
阿新 • • 發佈:2021-01-13
活動安排問題 :定義比較器 按照活動的結束時間來進行排序
public class Program{
public int start;
public int end;
public Program(int start, int end) {
this.start = start;
this.end = end;
}
}
public static class ProgramComparator implements Comparator<Program>{
@Override
public int compare (Program o1, Program o2) {
return o1.end - o2.end;
}
}
//timePoint 表示開始時間點
public static int bestArrange(Program[] programs, int timePoint) {
Arrays.sort(programs, new ProgramComparator());
int result = 0;
for(int i = 0; i < programs.length; i++) {
if(timePoint <= programs[i].start) {
result++ ; //可以安排的活動數目
timePoint = programs[i].end;
}
}
return result;
}
字典序問題:給一個字串,按照返回最大的字串
//字串排序問題
public static class MyComparator implements Comparator<String>{
//用compareTo來比較字串
public int compare(String o1, String o2) {
return (o1 + o2).compareTo(o2 + o1);
}
}
public static String lowestString (String[] strs) {
if(strs == null | strs.length == 0) return null;
Arrays.sort(strs, new MyComparator());
StringBuilder res = new StringBuilder();
for(int i = 0; i < strs.length; i++) {
res.append(strs[i]);
}
return res.toString();
}
題目描述:
//哈夫曼樹 最小花費的類似問題
public static int lessMoney(int[] nums) {
PriorityQueue<Integer> pQ = new PriorityQueue<Integer>();
for(Integer num : nums) {
pQ.add(num); //放進小根堆中 從小到大進行排列
}
int sum = 0;
int cur = 0;
while(pQ.size() > 1) {
//每次拿出最小的兩個數 進行相加 然後又放到小根堆中去
cur = pQ.poll() + pQ.poll();
sum += cur;
pQ.add(cur);
}
return sum;
}
題目描述:關於做專案的利潤,給兩個陣列,其中一個為profits,一個為costs,給定k和w,其中k為可做的專案個數,w為啟動資金,求最大的利潤數
//花費一樣時,按照利潤來排序
public static class Node{
public int p; //利潤
public int c; //花費
public Node(int p, int c) {
this.c = c;
this.p = p;
}
}
//定義兩個比較器
public static class MinCostComparator implements Comparator<Node>{
@Override
public int compare(Node o1, Node o2) {
return o1.c - o2.c;
}
}
public static class MaxProfitComparator implements Comparator<Node>{
@Override
public int compare(Node o1, Node o2) {
return o2.p - o1.p;
}
}
//k 最多選多少個專案 w為初始資金
public static int findMaximizedCapital(int k, int W, int[] profits, int[] costs) {
//其中minCostQ按照花費來存放專案節點
PriorityQueue<Node> minCostQ = new PriorityQueue<Node>(new MinCostComparator());
//maxProfitQ存放解鎖的專案,按照利潤來進行排列
PriorityQueue<Node> maxProfitQ = new PriorityQueue<Node>(new MaxProfitComparator());
for(int i = 0; i < profits.length; i++) {
minCostQ.add(new Node(profits[i], costs[i]));
}
for(int i = 0; i < k; i++) {
while(!minCostQ.isEmpty() && minCostQ.peek().c <= W) {
maxProfitQ.add(minCostQ.poll());
}
//即有的錢不足於解鎖新的專案 所以提前結束
if(maxProfitQ.isEmpty()) return W;
W += minCostQ.poll().p;
}
return W;
}
參考牛客網左神的演算法講解視訊牛客網