Zerojudge m370. 機械鼠

題解

把食物排序後,用二分搜尋法找到老鼠往右可以吃的第一個食物的位置,即可算出有幾個食物在老鼠的右邊&左邊

也可以用for迴圈遍歷食物位置

Python 解答

#二分搜
import bisect

x, n = map(int, input().split())
food = sorted(map(int, input().split())) #sorted會反回list

right_first_pos = bisect.bisect_right(food, x)

right = (n-1)-right_first_pos+1
left = (right_first_pos-1)-0+1

if right > left:
    print(right, food[-1])
else:
    print(left,food[0])
#遍歷食物位置
x, n = map(int, input().split())
food = list(map(int, input().split()))

lcount = rcount = 0
llast, rlast = float('inf'), float('-inf')

for f in food:
    if f<x:
        lcount+=1
        llast = min(llast, f)
    else:
        rcount+=1
        rlast = max(rlast, f)

if lcount>rcount:
    print(lcount, llast)
else:
    print(rcount, rlast)