提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
对于贪心,大多数同学都会感觉,不就是常识嘛,这算啥算法,那么本周的题目就可以带大家初步领略一下贪心的巧妙,贪心算法往往妙的出其不意。
一、力扣134. 加油站
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int curGas = 0;
int totalGas = 0;
int index = 0;
for(int i = 0; i < gas.length; i ++){
curGas += gas[i] - cost[i];
totalGas += gas[i] - cost[i];
if(curGas < 0){
curGas = 0;
index = (i+1)%gas.length;
}
}
if(totalGas < 0){
return -1;
}
return index;
}
}
二、力扣135. 分发糖果
class Solution {
public int candy(int[] ratings) {
int[] res = new int[ratings.length];
Arrays.fill(res,1);
for(int i = 1; i< ratings.length; i ++){
if(ratings[i] > ratings[i-1] && res[i] <= res[i-1]){
res[i] = res[i-1]+1;
}
}
for(int i = ratings.length-2; i >= 0; i --){
if(ratings[i] > ratings[i+1] && res[i] <= res[i+1]){
res[i] = res[i+1]+1;
}
}
return Arrays.stream(res).sum();
}
}
三、力扣860. 柠檬水找零
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0, ten = 0, twenty = 0;
for(int i = 0; i < bills.length; i ++){
switch (bills[i]){
case 5 :
five ++;break;
case 10 :
if(five <= 0){
return false;
}
five --;
ten ++;break;
case 20 :
if(five >= 1 && ten >= 1){
twenty ++;
ten --;
five --;break;
}else if(five >= 3){
twenty ++;
five -= 3;break;
}else{
return false;
}
}
}
return true;
}
}
四、力扣406. 根据身高重建队列
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people,(a,b)->{
if(a[0] == b[0]){
return a[1] - b[1];
}else{
return b[0] - a[0];
}
});
List<int[]> res = new ArrayList<>();
for(int[] a: people){
res.add(a[1],a);
}
return res.toArray(new int[people.length][]);
}
}
本文介绍了四个基于贪心策略的LeetCode题目:加油站加油路径优化、分发糖果以最大化满意度、柠檬水找零的可行性判断以及根据身高重构队列。展示了如何运用贪心思想解决实际问题。
881

被折叠的 条评论
为什么被折叠?



