如何改善while循环的运行时间

时间:2019-03-03 04:54:29

标签: python

我正在尝试使用贪婪算法来解决在旅途中为汽车加油最少次数的问题。不幸的是,到目前为止,我的代码已经超过了解决此问题的时间限制。

我想问问题是否来自嵌套的while循环,因为这似乎是迭代次数最多的过程。这是代码:

def compute_min_refills(distance, tank, stations):
trip = distance
dist_traveled = 0

tank_capacity = tank
refills = 0 ##keeps track of total refills 

stations = stations
stations.append(trip) 

if tank > trip:
    return 0
elif station[-1] - station[-2] > tank:
    return -1
else:
    dist_traveled = tank
    while dist_traveled < trip:
        n = 0 
        while stations[n] <= dist_traveled:
            n+=1 
        if dist_traveled - stations[n-1] <= tank:
            refills+=1
        else:
            return -1
        dist_traveled = stations[n-1] + tank
        stations = stations[n-1:]
    return y

约束如下:

1 <距离<10 ^ 5

1 <战车<400

stations是一个最多包含300个元素的数组。

这是我第一次处理运行时问题,因此,即使是如何解决该问题的任何建议也将不胜感激。

1 个答案:

答案 0 :(得分:0)

您有几个错误。首先,您似乎假设function readurl(a) { input=document.getElementById('input'+a); if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { document.getElementById('blah'+a).src=e.target.result; }; reader.readAsDataURL(input.files[0]); } }已排序,但我看不到保证的地方。即使是,您的<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div class="new_img_container" > <label id="file">Upload image <input onchange="readurl(1)" id="input1" name="product_img" type="file" name="image" size="60" required> </label> <br> <img id="blah1" src="../images/product_image.png" alt="product_image" > </div> <br><br> <div class="new_img_container" > <label id="file">Upload image <input onchange="readurl(2)" id="input2" name="product_img" type="file" name="image" size="60" required> </label> <br> <img id="blah2" src="../images/product_image.png" alt="product_image" > </div> </body> </html>追加也可能会破坏它。

station

append(trip)elif station[-1] - station[-2] > tank: return -1 可能无关紧要,因为它们可能超出行程范围。而且,它们甚至可能不存在。

station[-1]

可能的arrayIndexOutOfBounds。

station[-2]

同一问题。

while stations[n] <= dist_traveled:
   n+=1 

最好只在外部while循环之外设置if dist_traveled - stations[n-1] <= tank: (并在不同的迭代中重用n = 0 ... stations = stations[n-1:] )。

n = 0

可能是TL的原因。 n满足此条件;之后,您将为if dist_traveled - stations[n-1] <= tank 分配与之前完全相同的值。测试:您在坐标dist_traveled = stations[n-1] + tankdist_traveled处有测站。