我一開始寫出這個版本的的程式碼 (python)
n = int(input())data = tuple(map(int, input().split()))idx = int(input()) - 1offset = 1 if idx < n - 2 and data[idx + 1] < data[idx - 1] else -1while 0 <= idx < n and data[idx + offset] <= data[idx]: idx += offsetprint(idx + 1)
結果很順利的得到 AC,但其實這是錯誤答案。
因為這個程式碼並未考慮到當起點位置在第一個位置時,方向只能是往右。
若起點位置是第一個位置,在決定方向時,會比較第2個和「最後一個」位置的值的大小,並決定該往哪走,
如果「最後一個」位置的數字比較小,那這段程式碼就會選擇往左走。
如果測資長這樣:
6 4 2 1 3 5 1 1
用這段程式碼會輸出 0
但實際上應輸出 3