Create First Unique Character in a String.md#17
Conversation
| - 各時点で登録しているmapから、可能な限り削除する | ||
| - step1は最後にまとめて判定するが、この方法は判定しながら進むイメージ | ||
| - one-wayで処理できることがメリット | ||
| - 「a,b,b,b,b,b,......」のような時はqueueがずっと伸びるので、空間計算量はかかる |
There was a problem hiding this comment.
コメントありがとうございます!
while (!characters.empty() && character_to_frequency[characters.front().c] >= 2) つまりqueueの先頭のカウントの出現頻度が2以上か、で毎回popするかを決めているので
abbbbbb....の時はqueueは伸び続けると思います
この場合は、最後までqueueからは取り出されることがなく、最後に先頭の('a',0)が取り出されて答えとして0が返されると思っています
There was a problem hiding this comment.
if (character_to_frequency[c] == 1) {
characters.push({c, index});
}これだけで抑えられますね!
教えていただきありがとうございます
| } | ||
| return -1; //not found | ||
| } | ||
| }; |
There was a problem hiding this comment.
いいと思います。
removeする形よりもシンプルで分かりやすいですよね。
| 9分で3回Accept | ||
|
|
||
| #### 2周目の宿題 | ||
| - double-linked-listの実装 |
There was a problem hiding this comment.
https://www.coursera.org/lecture/data-structures/doubly-linked-lists-jpGKD
↑
これわかりやすかったです。
あと、doubly-linked listが書けるようになると、
LRU cacheも書けるようになるので、挑戦してもいいかもしれません。
There was a problem hiding this comment.
ありがとうございます!LRU cacheも一緒に実装できるよう、こちらの教材も利用してみます!
| } | ||
| std::vector<int> unique_character_indexes; | ||
| for (auto [_, index] : unique_character_to_index) { | ||
| unique_character_indexes.push_back(index); |
There was a problem hiding this comment.
vectorを用意せずここでminを使い最小値をとるというやり方もあると思います
There was a problem hiding this comment.
ありがとうございます!
辞書valueの最少値を求めるために、min_elementを使用してみたのですが、もっと簡単に求める方法はあるでしょうか?
class Solution {
public:
int firstUniqChar(const std::string& s) {
std::map<char, int> unique_character_to_index;
std::set<int> removed_characters;
for (int index = 0; index < s.size(); index++) {
auto c = s[index];
if (removed_characters.contains(c)) {
continue;
}
if (unique_character_to_index.contains(c)) {
unique_character_to_index.erase(c);
removed_characters.insert(c);
continue;
}
unique_character_to_index[c] = index;
}
if (unique_character_to_index.empty()) {
return -1; //not found
}
auto itr_for_min_index = std::min_element(
unique_character_to_index.begin(), unique_character_to_index.end(),
[](const auto& a, const auto& b) {
return a.second < b.second;
}
);
return (*itr_for_min_index).second;
}
};There was a problem hiding this comment.
こんな感じでしょうか。
indexとして取りうる最大値(10^5)を用意しておいて
unique_character_to_indexと大小比較していく形です。
int min_index = 100000;
for (const auto& [_, index] : unique_character_to_index) {
min_index = std::min(min_index, index);
}
return min_index;| - const& 参照 https://github.com/colorbox/leetcode/pull/29/files#r1861423426 | ||
| - 参照は場所を検索するステップがかかるため、レジスタ幅(アーキテクチャによるが、4byte or 8byte)に乗るなら参照しないほうがいい | ||
| - 参照は「名前」のようなものという話 https://github.com/colorbox/leetcode/pull/29/files#r1861617719 | ||
| - あんまり理解できていない、けど要は場所を実体の名前にするということだろうか。コンビニのタバコを本来は棚の場所を意味する「3番」みたいに指定することに似てる? |
| }; | ||
| ``` | ||
|
|
||
| double-linked-listの実装は2周目の宿題 |
This Problem
First Unique Character in a String
Next Problem
Find K Pairs with Smallest Sums