###前提・実現したいこと
ネット上の練習問題(本の整理)を解いているのいるのですが、実行時間が長すぎて不合格となってしまいます。どのようにプログラムを書けば省メモリ・高速になりますか?
###発生している問題・エラーメッセージ
制限時間は16秒なのですがこれをオーバーしてしまいます。
メモリは512MBらしいです。
###該当のソースコード
number_of_books=int(input()) booksarray=list(map(int,input().rstrip().split())) count=0 for i in range(number_of_books): if booksarray[i]==i+1: pass else: temporal=booksarray[i] booksarray[booksarray.index(i+1)]=temporal booksarray[i]=i+1 count+=1 print(count)
num=int(input()) books=' '+input().rstrip()+' ' count=0 offset=1 for i in range(num): idnumber=books[offset] j=1 while True: if books[offset+j]!=' ': idnumber+=books[offset+j] j+=1 else: break offset+=len(str(i+1))+1 if idnumber==str(i+1): pass else: temporal=idnumber books=books.replace(' '+str(i+1)+' ',' '+str(temporal)+' ') books=books.replace(' '+str(temporal)+' ',' '+str(i+1)+' ',1) count+=1 print(count)
###試したこと
リストではメモリを食いすぎると思い、文字列で同じことをやってみましたがやはりタイムオーバーとなってしまいました。
###補足情報(言語/FW/ツール等のバージョンなど)
(自分側に実行環境があるわけではないので、サードパーティ製のモジュール等は使えないです。)
お仰せの通りNumpyは使えました。
しかし、このアルゴリズムではやはりタイムオーバーとなってしまいました。
回答3件
あなたの回答
tips
プレビュー