数値が与えられると、合計がその数値に等しい、与えられた配列内のすべての可能なインデックスペアを見つける必要があります。私は現在、次のアルゴリズムを使用しています。
def myfunc(array,num):
dic = {}
for x in xrange(len(array)): # if 6 is the current key,
if dic.has_key(num-array[x]): #look at whether num-x is there in dic
for y in dic[num-array[x]]: #if yes, print all key-pair values
print (x,y),
if dic.has_key(array[x]): #check whether the current keyed value exists
dic[array[x]].append(x) #if so, append the index to the list of indexes for that keyed value
else:
dic[array[x]] = [x] #else create a new array
これはO(N)
間に合うでしょうか?そうでない場合は、それを実現するために何をすべきですか?O(N)
そして、いずれにせよ、補助的なデータ構造を使用せずに時間内に実行することは可能ですか?