剑指OFFER笔记_14_2_剪绳子(贪婪算法)_JAVA实现

题目:剪绳子(贪婪算法)

  • 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1]…k[m-1] 。请问 k[0]*k[1]*…*k[m-1]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。

解题思路

  • 此题如果每一刀都将绳子剪出一个长为3的段来,是可以让结果最大的,结果证明比较复杂,可以参考下图中LeetCode官方给出的证明:
    在这里插入图片描述
  • 因此我们也按照此方案去切割绳子。
  • 在写代码的时候,需要考虑到特殊情况的处理,也就是当n比较小的时候。
  • 此外我前几次在LeetCode的运行结果都是可以通过一部分测试用例,但是当n较大时,进行取余后的结果有细微的差别(九位数的后两位不同),我意识到应该是取余的操作时机不一样。
  • 最初我用的是Math.pow()去求幂,我后来尝试自己写了一个quickPower()函数,在每一次乘的时候都进行取余,最终结果就能够通过LeetCode的测试了。如果不是为了通过力扣测试,没有必要单独写一个函数求幂。

代码

函数主体部分代码

package q14_02;

/**
 * 贪婪算法,每次剪3,当n=4时剪2
 */
public class Solution {
    public int cuttingRope(int n) {
        if (n < 2)
        {
            return 0;
        }
        if (n == 2)
        {
            return 1;
        }
        if (n == 3)
        {
            return 2;
        }
        if (n == 4)
        {
            return 4;
        }

        int timesOfThree = n / 3;
        int timesOfTwo = 0;
        double result = 1;
        if (n - 3 * timesOfThree == 1)
        {
            timesOfThree--;
            timesOfTwo += 2;
        }else
        {
            timesOfTwo += (n - 3 * timesOfThree) / 2;
        }

        if(timesOfThree != 0)
        {
            result = quickPower(3, timesOfThree)%(1e9+7);
        }
        if(timesOfTwo != 0)
        {
            result *= quickPower(2, timesOfTwo);
        }

        return (int)(result%(1e9+7));
    }
    
    public double quickPower(double base, int power)
    {
        if (power == 0)
        {
            return 1;
        }
        if (power == 1)
        {
            return base;
        }
        double result = base;
        for (int i = 0; i < power-1; i++)
        {
            result = (result*base) % (1e9+7);
        }
        return result;
    }
}

测试部分代码

package q14_02;

public class TestApp {
    public static void main(String[] args) {
        Solution s = new Solution();
        double currentTime = System.currentTimeMillis();
        System.out.println(currentTime);
        for (int i = 0; i < 121; i++) {
            System.out.println(i + " is : " + s.cuttingRope(i));
        }
        double currentTime2 = System.currentTimeMillis();
        System.out.println((currentTime2-currentTime)/1000);
    }
}

运行结果截图

在这里插入图片描述
在这里插入图片描述

LeetCode运行截图

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值