博客
关于我
Leetcode每日刷题【易】--Day 1
阅读量:757 次
发布时间:2019-03-23

本文共 1080 字,大约阅读时间需要 3 分钟。

为了将连分数转换为最简分数,我们从最右端开始处理每个系数,逐步向外扩展分子和分母。这种方法确保了我们正确地处理了每个层次的分式。

class Solution:    def fraction(self, cont: List[int]) -> List[int]:        if not cont:            return [0, 1]        numerator = cont[-1]        denominator = 1        for i in range(len(cont) - 2, -1, -1):            next_num = cont[i] * numerator + denominator            next_den = numerator            numerator, denominator = next_num, next_den        return [numerator, denominator]

解决方法:我们的目标是将连分数转换为一个最简分数。连分数的形式通常为 a0 + 1/(a1 + 1/(a2 + ... + 1/an))。为了将这个表达式转换为普通分数形式,我们可以从最右边的系数开始处理,每次扩展上一层的分子和分母。

初始化:

  • 从最右边的系数开始,初始化为分子和分母分别为该数和1。

迭代处理:

  • 从倒数第二个系数开始,逐步处理每个系数。
  • 对于每个系数 a_i,计算新的分子和分母:
    • 新的分子为 a_i * previous_numerator + previous_denominator
    • 新的分母为 previous_numerator
  • 更新当前的分子和分母,继续处理下一个较高的系数。

示例:输入:cont = [3, 2, 0, 2]处理步骤:

  • 初始化:numerator = 2, denominator = 1
  • 处理 i=2(元素 0):
    • numerator = 0 * 2 + 1 = 1
    • denominator = 2
  • 处理 i=1(元素 2):
    • numerator = 2 * 1 + 2 = 4
    • denominator = 1
  • 处理 i=0(元素 3):
    • numerator = 3 * 4 + 1 = 13
    • denominator = 4返回 [13, 4],即最简分数 13/4
  • 代码解释:

    • 初始化分子和分母。
    • 正向遍历反转的列表,逐步更新分子和分母,确保每一步的正确性。
    • 最终返回化简后的分子和分母。

    转载地址:http://uxpzk.baihongyu.com/

    你可能感兴趣的文章
    NoSQL&MongoDB
    查看>>
    NoSQL介绍
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>