LoginSignup
0
0

【Python】配列内の最小要素の最小 index を取得する

Posted at

最小要素の最左 index がほしいことがあります。

任意配列の場合のコード

a = [3, 1, 4, 1, 5]

A = [(a[i], i) for i in range(len(a))]
print(min(A)[1])

(値, index) のタプルにすることで、値最小のうち index 最小のものが選択されます。

自然数配列の場合のコード

a = [3, 1, 4, 1, 5]

BASE = 10 ** 6
A = [a[i] * BASE + i for i in range(len(a))]
print(min(A) % BASE)

十分大きな値で乗じてから index を足しておくと、除算で index が取れるようになります。

応用

セグメント木にタプルを載せると遅いし、min を改造するのも遅い…… というときに使えます。ただの配列操作で大きな恩恵はありませんが、高度なデータ構造に載せる際に恩恵が得られます。

おわり

初心者向け!

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0