首页 > 解决方案 > 超出时间限制错误 - 当我尝试运行 Python 3 代码时

问题描述

超出时间限制 您的代码未在时间限制内执行。请优化您的代码。有关执行时间限制的更多信息,请参阅环境页面

这是 Hackerrank 上问题的链接。

https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'repeatedString' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
#  1. STRING s
#  2. LONG_INTEGER n
#

def repeatedString(s, n):
    Write your code here
    i = 0
    aCount = 0
    
    while i <= n:
        if 'a' == s[i]:
            aCount += 1
            ++i
        else:
            ++i
            
            print(aCount)
            return aCount 

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    n = int(input().strip())

    result = repeatedString(s, n)

    fptr.write(str(result) + '\n')

    fptr.close()

标签: pythonpython-3.xalgorithm

解决方案


您正在从 0 到 n 运行 while 循环,n 的最大值为 10^12。在最坏的情况下,while 循环运行 10^12 次。这就是为什么时间超过了。尝试优化代码。

试试这个代码

def repeatedString(s, n):
    #Write your code here
    aCount = 0
    
    for i in range(len(s)):
        if 'a' == s[i]:
            aCount += 1
    aCount*=(n//len(s))
    x=n%len(s)
    for i in range(x):
        if 'a' == s[i]:
            aCount += 1
            
    return aCount 

推荐阅读