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

    你可能感兴趣的文章
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    node
    查看>>
    node exporter完整版
    查看>>
    node HelloWorld入门篇
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node JS: < 二> Node JS例子解析
    查看>>
    Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>
    Node 裁切图片的方法
    查看>>
    node+express+mysql 实现登陆注册
    查看>>
    Node+Express连接mysql实现增删改查
    查看>>
    node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
    查看>>
    Node-RED中Button按钮组件和TextInput文字输入组件的使用
    查看>>
    vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
    查看>>
    Node-RED中Switch开关和Dropdown选择组件的使用
    查看>>
    Node-RED中使用exec节点实现调用外部exe程序
    查看>>
    Node-RED中使用function函式节点实现数值计算(相加计算)
    查看>>