From 663414a44605ae2d0cd95fdfc748343cd83bfba0 Mon Sep 17 00:00:00 2001 From: markilue <745518019@qq.com> Date: Wed, 9 Nov 2022 16:27:54 +0800 Subject: [PATCH] =?UTF-8?q?leecode=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leecode/greedy/LemonadeChange.java | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 Leecode/src/main/java/com/markilue/leecode/greedy/LemonadeChange.java diff --git a/Leecode/src/main/java/com/markilue/leecode/greedy/LemonadeChange.java b/Leecode/src/main/java/com/markilue/leecode/greedy/LemonadeChange.java new file mode 100644 index 0000000..cf617e0 --- /dev/null +++ b/Leecode/src/main/java/com/markilue/leecode/greedy/LemonadeChange.java @@ -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 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; + + } +}