博客
关于我
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/

    你可能感兴趣的文章
    OpenStreetMap初探(一)——了解OpenStreetMap
    查看>>
    openSUSE 13.1 Milestone 2 发布
    查看>>
    openSUSE推出独立 GUI 包管理工具:YQPkg,简化了整个软件包管理流程
    查看>>
    OpenVP共用账号 一个账号多台电脑登录
    查看>>
    OpenVSwtich(OVS)Vlan间路由实战 附实验环境
    查看>>
    Openwrt LuCI模块练习详细步骤
    查看>>
    openwrt_git_pull命令提示merger冲突时如何解决?
    查看>>
    OpenWrt包管理软件opkg的使用(极路由)
    查看>>
    OpenWrt固件编译刷机完全总结
    查看>>
    Open××× for Linux搭建之二
    查看>>
    Open×××有线网络时使用正常,无线网络时使用报错的解决方案
    查看>>
    Opera Mobile Classic Emulator
    查看>>
    Operation not supported on read-only collection 的解决方法 - [Windows Phone开发技巧系列1]
    查看>>
    OperationResult
    查看>>
    Operations Manager 2007 R2系列之仪表板(多)视图
    查看>>
    operator new and delete
    查看>>
    operator new 与 operator delete
    查看>>
    operator() error
    查看>>
    OPPO K3在哪里打开USB调试模式的完美方法
    查看>>
    oppo后端16连问
    查看>>