[LeetCode] 1553. Minimum Number of Days to Eat N Oranges

There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:

  • Eat one orange.
  • If the number of remaining oranges (n) is divisible by 2 then you can eat  n/2 oranges.
  • If the number of remaining oranges (n) is divisible by 3 then you can eat  2*(n/3) oranges.

You can only choose one of the actions per day.

Return the minimum number of days to eat n oranges.

Example 1:

Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange,  10 - 1 = 9.  
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. 
Day 4: Eat the last orange  1 - 1  = 0.
You need at least 4 days to eat the 10 oranges.

Example 2:

Input: n = 6
Output: 3
Explanation: You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange  1 - 1  = 0.
You need at least 3 days to eat the 6 oranges.

Example 3:

Input: n = 1
Output: 1

Example 4:

Input: n = 56
Output: 6

Constraints:

  • 1 <= n <= 2*10^9

吃掉N个橘子的最少天数。

题意是给一个数字N代表橘子的个数,现在有三种吃法,每次吃橘子的时候你只能选择一种吃法。请问如何吃才能尽快吃完橘子,吃的次数最少。吃法如下,

  • 吃掉一个橘子。
  • 如果剩余橘子数 n 能被 2 整除,那么你可以吃掉 n/2 个橘子。
  • 如果剩余橘子数 n 能被 3 整除,那么你可以吃掉 2*(n/3) 个橘子。

这个题我一开始做的时候试着用贪心的思路。因为乍一看如果橘子数量很大而且剩余橘子数量能被3整除的话,一直选择第三种吃法似乎是最快的;如果剩余橘子数量不能被3整除,则试试看能不能被2整除;如果再不行则试着只吃掉一个橘子。这个思路会超时。

一个能通过的思路是BFS。每次判断的时候,三种方法都试一下,将三种方法吃剩下的橘子数放入queue,就跟树的层序遍历一样。如此遍历,最后看看需要几轮能把橘子吃完,返回那个轮数。这样常规地做BFS思路是没问题,但是依然会超时。

[LeetCode] 1553. Minimum Number of Days to Eat N Oranges

既然常规的BFS会超时,同时发现其实有一些中间结果是重复出现的,那么就试着用一个hashset记录一下中间结果。如果再次出现,则直接跳过,不需要再次放入queue。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int minDays(int n) {
 3         int steps = 0;
 4         Queue<Integer> queue = new LinkedList<>();
 5         queue.offer(n);
 6         HashSet<Integer> set = new HashSet<>();
 7         while (!queue.isEmpty()) {
 8             int size = queue.size();
 9             for (int i = 0; i < size; i++) {
10                 int cur = queue.poll();
11                 if (set.contains(cur)) {
12                     continue;
13                 }
14                 set.add(cur);
15                 if (cur == 0) {
16                     return steps;
17                 }
18                 if (cur % 3 == 0) {
19                     queue.offer(cur / 3);
20                 }
21                 if (cur % 2 == 0) {
22                     queue.offer(cur / 2);
23                 }
24                 if (cur >= 1) {
25                     queue.offer(cur - 1);
26                 }
27             }
28             steps++;
29         }
30         return steps;
31     }
32 }

 

LeetCode 题目总结

上一篇:201509-2 日期计算 Java


下一篇:2020-03-05