leetcode6: ZigZag Conversion ——python

题目

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);
  • Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
  • Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

优秀代码###

class Solution:
    def convert(self, s, numRows):
        if numRows == 1 or numRows >= len(s): return s
        row, direction, res = 0, -1, [""] * numRows
        for char in s:
            res[row] += char
            if row == 0 or row == numRows - 1: direction *= -1 
            row += direction
        return "".join(res) 

反例代码

def convert(s,num):
    b = []
    c = ''
    i = 0
    while i<len(s):
        x = -2
        for t in range(0,num+num-2):
            if i+t<len(s):
                if t > num -1:
                    b[x] += s[i+t]
                    x -= 1
                    continue
                if t > len(b) - 1:
                    b.append('')
                b[t] += s[i+t]
        i += (num + num - 2)
    print(b)
    for a in b:
        c += a
    return c
print(convert('A',3))

代码对比

第二个答案的精妙之处在于引入的中间变量step可以变为-1,这样极为简单,

如果计算复杂度,可以发现第一个答案有3个循环,第二个答案有一个循环,第一个是n^2+n ,第二个是n

Time limited

刷LeetCode好多次遇到time limited这样的问题,这样就是时间复杂度太高了,那么如何计算复杂度呢,如何降低复杂度呢?

首先了解一下几个概念。一个是时间复杂度,一个是渐近时间复杂度。前者是某个算法的时间耗费,它是该算法所求解问题规模n的函数,而后者是指当问题规模趋向无穷大时,该算法时间复杂度的数量级。

当我们评价一个算法的时间性能时,主要标准就是算法的渐近时间复杂度,因此,在算法分析时,往往对两者不予区分,经常是将渐近时间复杂度T(n)=O(f(n))简称为时间复杂度,其中的f(n)一般是算法中频度最大的语句频度。

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值