Conversation
| return len(nums) | ||
| if nums[-1] == target: | ||
| return len(nums) - 1 | ||
| smaller, greater = 0, len(nums) - 1 |
There was a problem hiding this comment.
smaller greater を同一の行で定義する必然性はあまり感じられませんでした。 2 行に分けて書いたほうが、読み手にとって読みやすいように思います。
| return len(nums) - 1 | ||
| smaller, greater = 0, len(nums) - 1 | ||
| while greater - smaller > 1: | ||
| mid = smaller + (greater - smaller) // 2 |
There was a problem hiding this comment.
Python では整数はほとんどの場合でオーバーフローしないため、 mid = (smaller + greater) // 2 で十分だと思います。
|
|
||
| 引数`nums` のサイズを$N$として, | ||
| 時間$O(\log N)$, 空間 $O(1)$. | ||
| $N$があまりに巨大なら`smaller`, `greater`, `mid` あたりのサイズがでかくなって空間$O(\log N)$に. |
There was a problem hiding this comment.
N が大きくなろうが、smaller などのインデックスは O(1) ではないかと思いました。
There was a problem hiding this comment.
コメントありがとうございます.
意図としては,int型の変数に対するCPythonの内部表現のメモリサイズについてでした.適宜リファレンスなりするべきでしたね.以下に簡単な検証結果も併せて記載します.
リファレンス
CPythonの多倍長整数の表現を見てみますと,
多倍長整数の変数の値はいくつかの30または15bitの整数で内部表現されていることが分かります.
Long integers are made up of a number of 30- or 15-bit digits, depending on
the platform.
また,実装上は,digit 型( = uint32_t または unsigned short)の配列 ob_digit で管理しており,使っていない2ないし1bitはフラグbitとして扱われているようです.
検証
さて,検証コードを動かしてみました; xのそれぞれについて,
その値 (x ),ビット長 (x.bit_length()),内部表現で使われる符号なし32bit整数の個数 (#32bit_integers),その配列のサイズ(in byte, 32bit_integer_array),および変数xのサイズ(in byte, x.__sizeof()__)
を計算・取得して出力するものです.
検証コード
import math
def memory_profile(x: int):
power = int(math.log10(x))
bit_length = x.bit_length()
num_of_32bit_integers = -(-bit_length // 30)
array_size_in_bytes = 4 * num_of_32bit_integers
print(
f"x = 10 ** {power:>5}, x.bit_length= {bit_length:>6}, #32bit_integers = {num_of_32bit_integers:>4}, 32bit_integer_array = {array_size_in_bytes:>5}, {x.__sizeof__() = }"
)
one = 1
print(f"{one.__sizeof__() = }")
for i in range(5):
too_big = 10 **(4 * 10**i)
memory_profile(too_big)出力結果は以下です;実行結果としても,多倍長整数は30bitに収まらない範囲の整数に対処するために,適宜メモリを大きく確保していることが分かります.
one.__sizeof__() = 28
x = 10 ** 4, x.bit_length= 14, #32bit_integers = 1, 32bit_integer_array = 4, x.__sizeof__() = 28
x = 10 ** 40, x.bit_length= 133, #32bit_integers = 5, 32bit_integer_array = 20, x.__sizeof__() = 44
x = 10 ** 400, x.bit_length= 1329, #32bit_integers = 45, 32bit_integer_array = 180, x.__sizeof__() = 204
x = 10 ** 4000, x.bit_length= 13288, #32bit_integers = 443, 32bit_integer_array = 1772, x.__sizeof__() = 1796
x = 10 ** 40000, x.bit_length= 132878, #32bit_integers = 4430, 32bit_integer_array = 17720, x.__sizeof__() = 17744
以上のように,内部表現では30bit整数を用いるため,「
問題
https://leetcode.com/problems/search-insert-position/description/
成果物所在
35._Search_Insert_Position/memo.mdがステップ1~3までをまとめたmdファイルです.次に取り組む問題のリンク
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description