Conversation
| class Solution { | ||
| public: | ||
| bool canConstruct(string ransomNote, string magazine) { | ||
| int char_count[26]; |
There was a problem hiding this comment.
int char_count[26] = {0} のように明示的に初期化してあるほうがよりわかりやすいかと思いました。(自分はC++を書いたことがないので、書かないほうが自然だったら申し訳ありません。)
あと、HashMapと配列それぞれへのアクセスですが、Pythonだと速度比で 辞書: 配列 = 3.5: 2.9 ぐらいでした。C++での高速化の目安になるかはわかりませんが参考までに。
There was a problem hiding this comment.
レビューありがとうございます、初期化の観点が抜けていました。
383/step1.cpp
Outdated
| map<char, int> character_count; | ||
| for (char c: magazine) { | ||
| if (!character_count[c]) { | ||
| character_count[c] = 0; |
383/step1.cpp
Outdated
| } | ||
|
|
||
| for (char c: ransomNote) { | ||
| if (!character_count[c] || character_count[c] <= 0) { |
There was a problem hiding this comment.
https://cpprefjp.github.io/reference/map/map/op_at.html
キー x に対応する値を返す。対応する要素が存在しない場合は、要素を値初期化して参照を返す。
左側は不要です。初期化したくなければ find, count, contains を使いましょう。
There was a problem hiding this comment.
ありがとうございます、[]を使うと初期化されるので存在確認は不要ということですね。
| Time O: O(N) | ||
|
|
||
| ransomに使用する文字が十分存在するかどうかをカウントすればよいと考える。 | ||
| magazineにある文字を高速にチェックできないといけないので、ハッシュ(map)にして高速化を考える。 |
There was a problem hiding this comment.
https://en.cppreference.com/w/cpp/container/map
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as Red–black trees.
There was a problem hiding this comment.
コメントありがとうございます、計算量をちゃんと理解できておりませんでした。
There was a problem hiding this comment.
そこではなくて、「ハッシュ(map)」と書いてあるけれども、C++ の map は、普通、キーがソートされているという制約から赤黒木で、ハッシュではないのです。
step1は不要な初期化やnullチェックを削除 step3は初期化を適切に行うように修正
| class Solution { | ||
| public: | ||
| bool canConstruct(string ransomNote, string magazine) { | ||
| int char_count[26]; |
There was a problem hiding this comment.
= {}; で zero-initialized されます。
C++11 からですね。
https://abseil.io/tips/146
383. Ransom Note