-
Notifications
You must be signed in to change notification settings - Fork 0
779. K-th Symbol in Grammar #47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
良いと思います。
良いと思います。 |
assert n >= 2 | ||
half_num_elements = 2 ** (n - 2) # 2**(n-1) // 2 | ||
assumption = 0 | ||
x = assumption |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
assumptionは不要な気がしました。(意図的だったらすみません。)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
一応意図的ではありました 🙏
この変数あった方が分かりやすいかな?と思って書きましたが諸説あるかも...
- 時間計算量: O((log n)^2) | ||
- 空間計算量: O(1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
これってどういう計算でしょうか。
最悪n-1回再起呼び出しがあって、whileループが最初n-1回から1つずつ減っていって、
(n-1) + (n-2) + ... + 1 = (n-1)(n-2)/2 で
時間がO(n^2)で、空間がO(n)かなと思いましたが勘違いしてますかね。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
たぶん何を n としているかが違っていて、桁数ではなくて引数の n 自体のことでしょう。
それだと空間は確かに O(log n) ですね。関数の呼び出しスタックがあります。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
O(1)は明らかに変ですね、ありがとうございます。
桁数ではなくて引数の n 自体のことでしょう
そのつもりで書きましたが、改めて考えるとよくわからなくなりました。 1 <= k <= 2**n - 1 の条件から、
空間計算量: k/2 <= power < k から k-power <= k/2 なので、kは再帰のたびに少なくとも半分に減っていくので再帰の数はO(log k), つまりO(n) で抑えられる。
時間計算量: 関数呼び出しのたびに毎回ln k 回ループを回すので、i番目の再帰のときのkの数をk(i)とすると、
a = O(log k) = O(n) なので、O((log k)^2) = O(n^2)
なのかなと計算して思いましたが、自信はないです
https://leetcode.com/problems/k-th-symbol-in-grammar/description/