leecode更新

This commit is contained in:
markilue 2022-11-09 16:27:54 +08:00
parent ba62bbc0a2
commit 663414a446
1 changed files with 135 additions and 0 deletions

View File

@ -0,0 +1,135 @@
package com.markilue.leecode.greedy;
import org.junit.Test;
import java.util.HashMap;
/**
* @BelongsProject: Leecode
* @BelongsPackage: com.markilue.leecode.greedy
* @Author: markilue
* @CreateTime: 2022-11-09 15:55
* @Description:
* TODO 力扣860题 柠檬水找零
* 在柠檬水摊上每一杯柠檬水的售价为 5 美元顾客排队购买你的产品按账单 bills 支付的顺序一次购买一杯
* 每位顾客只买一杯柠檬水然后向你付 5 美元10 美元或 20 美元你必须给每个顾客正确找零也就是说净交易是每位顾客向你支付 5 美元
* 注意一开始你手头没有任何零钱
* 给你一个整数数组 bills 其中 bills[i] 是第 i 位顾客付的账如果你能给每位顾客正确找零返回 true 否则返回 false
* @Version: 1.0
*/
public class LemonadeChange {
@Test
public void test(){
int[] bills = {5, 5, 5, 10, 20};
System.out.println(lemonadeChange(bills));
}
@Test
public void test1(){
int[] bills = {5,5,10,10,20};
System.out.println(lemonadeChange(bills));
}
/**
* 思路由于五块的钱啥都能找因此尝试尽可能的少用5块
* 使用map记录手头零钱{'面值'张数}
* 速度击败6.8%内存击败96.62%
* @param bills
* @return
*/
public boolean lemonadeChange(int[] bills) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < bills.length; i++) {
//10块需要找零
Integer fiveNum = map.getOrDefault(5,0);//5块的数量
if(bills[i]==5){
//5块不用找零
map.put(5,fiveNum+1);
continue;
}
//10块和20都需要5块没有五块直接返回false
if(fiveNum<=0){
return false;
}
Integer tenNum =map.getOrDefault(10,0);//10块的数量
if(bills[i]==10){
map.put(5,fiveNum-1);
map.put(10,tenNum+1);
continue;
}else {
//来的是20
//有十块先用十块
if(tenNum>0){
map.put(5,fiveNum-1);
map.put(10,tenNum-1);
}else {
//没有十块用5块
if(fiveNum<3){
return false;
}
map.put(5,fiveNum-3);
}
}
}
return true;
}
/**
* 代码随想录思路由于五块的钱啥都能找因此尝试尽可能的少用5块
* 使用five,ten来记录5块10块的数量
* 速度击败100%内存击败77.48%
* @param bills
* @return
*/
public boolean lemonadeChange1(int[] bills) {
int five=0;
int ten=0;
for (int i = 0; i < bills.length; i++) {
if(bills[i]==5){
//5块不用找零
five++;
continue;
}
//10块和20都需要5块没有五块直接返回false
if(five<=0){
return false;
}
if(bills[i]==10){
five--;
ten++;
}else {
//来的是20
//有十块先用十块
if(ten>0){
five--;
ten--;
}else {
//没有十块用5块
if(five<3){
return false;
}
five-=3;
}
}
}
return true;
}
}