Skip to content

Conversation

@Ryotaro25
Copy link
Owner

問題へのリンク
https://leetcode.com/problems/move-zeroes/description/

問題文(プレミアムの場合)

備考

次に解く問題の予告
Meeting Rooms

フォルダ構成
LeetCodeの問題ごとにフォルダを作成します。
フォルダ内は、step1.cpp、step2.cpp、step3.cpp、fill_zero.cpp、remove.cppとmemo.mdとなります。

memo.md内に各ステップで感じたことを追記します。

public:
void moveZeroes(vector<int>& nums) {
int last_zero_index = 0;
for (int i = 0; i < nums.size(); i++) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

型の違いや、暗黙の型変換が行われいてることを意識しているか?という点が少しだけ気になります。
当然に読んでいるかもしれませんが、もしまだでしたらこれらの項目を一読しておくことをお勧めいたします。
暗記する必要はないと思いますが、気になった時に調べられるようにというのと、気にする癖をつけるためです。
https://en.cppreference.com/w/cpp/language/const_cast
https://en.cppreference.com/w/cpp/language/static_cast
https://en.cppreference.com/w/cpp/language/dynamic_cast
https://en.cppreference.com/w/cpp/language/reinterpret_cast
https://en.cppreference.com/w/cpp/language/implicit_conversion
https://en.cppreference.com/w/cpp/language/explicit_cast

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

int については私はそんなにうるさくはないですが、size_t が unsigned integer であるというのは注意です。
for (int i = 0; i < num.size() - 1; ++i) という回し方をすると、num.size() が0を返したときにアンダーフローして止まらないことがあります。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@usatie @oda
レビュー頂きありがとうございます。
どこでキャストが行われているのか分かりやすくするよう可能な限り明示しようぐらいの感覚でした。
この辺りのドキュメント再読いたします。

num.size() が0を返したときにアンダーフローして止まらないことがあります。

これまで意識しておりませんでした。
他の問題でfor (int i = 0; i < num.size() - 1; ++i) このような条件式は使っていたと思いますが気付けませんでした。int型にキャストするのかループに渡す前にチェックするなど意識しておこうと思います。

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

あ、すみません。これをアンダーフローと呼ぶのは本来の用語としては誤りのようです。

アンダーフローは、float などで値が0に近くなりすぎて表現できなくなることで、signed integer が負に大きくなることもオーバーフローというようです。なお、unsigned の場合は module 2^n で考えているのでオーバーフローでもないとするのが本来の用語みたいです。

vectorのeraseではなか、<algorithm>のremoveを使う
前者だとforの中で使うのでO(n^2)となるが、後者だと舐めながら0を消して前に詰めるのでO(n)
removeは削除するのではなく、不要な要素を後ろに寄せているだけなので
詰め終わった箇所からnums.end()までゴミデータ?が残っているのは違和感
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

他の方のPRにも目を通していただいていたようなので読んでいると思いますが、Erase-Remove Idiom というのがあることくらいですかね。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.v62rdhwkdymb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants