codeforces706B 【python】

第一版寫法(如下)TLE了,所以得用二分啊

def get_result(wine_price,today_money):
    
    for i in range(len(wine_price)):
        if wine_price[i] > today_money:
            return i
    return len(wine_price)
    


n = int(raw_input())
wine_price = map(int,raw_input().split())
wine_price = sorted(wine_price)

q = int(raw_input())

for i in range(q):
    temp = int(raw_input())
    print get_result(wine_price,temp)

第二版寫法(如下)

def get_index(wine_price,today_money):
    left = 0
    right = len(wine_price) - 1
    while left < right:
        mid = (left + right)/2
        if wine_price[mid] <= today_money:
            left = mid + 1
        else:
            right = mid
    return right

def get_result(wine_price,today_money):
    result = get_index(wine_price,today_money)
    if result == (len(wine_price)-1) and today_money >= wine_price[-1]:
        result += 1
    return result
    
n = int(raw_input())
wine_price = map(int,raw_input().split())
wine_price = sorted(wine_price)

q = int(raw_input())

for i in range(q):
    temp = int(raw_input())
    print get_result(wine_price,temp)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章