刷题日记
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
Return the maximum number of ice cream bars the boy can buy with coins coins.
Note: The boy can buy the ice cream bars in any order.
完成任务需要的几个步骤
class Solution {public int maxIceCream(int[] costs, int coins) {Arrays.sort(costs);for(int i = 0; i < costs.length; i++) {if((coins -= costs[i]) < 0){return i;}}return costs.length;}
}
第一种实现风格,是我最终采用的风格,非常精炼,直接在if中包含了对coins的减法运算和结果的判断,同时减法和判断很直观。
public int maxIceCream(int[] costs, int coins) {Arrays.sort(costs);int res = 0;for (int i : costs) {if (coins >= i) {res++;coins -= i;}}return res;}
第二种实现风格,判断思路是对比每一次剩下的钱和当前ice cream bar的价格,但这种风格的缺点在于没有提前中止,即最终要把整个数组遍历一遍,时间消耗更大。
本文发布于:2024-02-05 05:08:56,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170724870563316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |