public class test23 { //问题:买苹果时,商店提供两种袋子,第一种一次装6个,第二种一次装8个 //小红有强迫症,使用的袋子必须最少且每个袋子必须装满。 //给一个正整数N的苹果数,返回至少使用多少袋子,如果无法满足小红的条件,返回-1 //暴力思路先找规律 public static int minBags(int apple){ if(apple < 0){ return -1; } int bag6 =-1; int bag8 = apple/8; int rest = apple - 8*bag8; while (bag8 >= 0 && rest <24){ int restUse6 = minBagBase6(rest); if(restUse6 != -1){ bag6 =restUse6; break; } rest =apple - 8*(--bag8); } return bag6 == -1 ? -1 : bag6 +bag8; } public static int minBagBase6(int rest){ return rest%6 == 0 ? (rest /6):-1; } //根据打表规律补出代码,时间复杂度O(1) public static int minBagAwesome(int apple){ if((apple & 1) != 0){ return -1; } if(apple <18){ return apple == 0 ? 0 : (apple ==6 || apple == 8) ? 1 : (apple == 12 || apple ==14 || apple == 16) ? 2 : -1; } return (apple -18)/8 +3; } //打印1到100内的苹果所装的最大袋子数,去发现规律 public static void main(String[] args) { for (int apple = 1; apple <= 100; apple++) { System.out.println(apple +":" + minBags(apple)); } } }
苹果装袋子问题(打表技巧)
最新推荐文章于 2024-08-12 16:47:32 发布