Conversation
|
|
||
| ### 解法を考える。 | ||
| - 整数配列nums、整数targetで、nums[i] + nums[j] = targetとなるインデックスi, jを探す | ||
| - 問題文から補数を探す、今回はハッシュマップ unordered_mapで良さそう |
There was a problem hiding this comment.
std::unordered_map (std::unordered_set) は std::map (std::set) より insert() が遅いようです。また、要素数が少ない時は std::unordered_map (std::unordered_set) のほうがメモリ使用量が大きいようです。
https://chromium.googlesource.com/chromium/src/+/HEAD/base/containers/README.md#std_unordered_map-and-std_unordered_set
https://groups.google.com/a/chromium.org/g/chromium-dev/c/rdxOHKzQmRY?pli=1
用途に応じて適切に使い分けるのが理想的です。一方、処理時間があまり問題とならない場合に、データ構造の選択に時間をかけるのは不適切です。このあたりはチームの平均的なやり方に合わせることをおすすめします
There was a problem hiding this comment.
@nodchip
コメント頂きありがとうございます。
ドキュメントもう少しじっくり読んでみます。
適切な評価をして、使い分けれるように今はじっくりと考えていきたいと思いますが、
一方、処理時間があまり問題とならない場合に、データ構造の選択に時間をかけるのは不適切です。このあたりはチームの平均的なやり方に合わせることをおすすめします
この辺りも頭の片隅に記憶しておきます。
| for (int i = 0; i < nums.size(); ++i) { | ||
| int complement = target - nums[i]; | ||
| if (num_to_index.count(complement)) { | ||
| return std::vector<int>{num_to_index[complement], i}; |
There was a problem hiding this comment.
initializer_list をコンストラクターにとる引数でインスタンス化して返すことができますので、
return {num_to_index[complement], i};のほうがシンプルで良いと思います。
There was a problem hiding this comment.
@nodchip
コメントありがとうございます。
initializer_list をコンストラクターにとる引数でインスタンス化して返すことができますので、
把握できてなかったので、referenceをじっくり読んで次回書けるようにしたいと思います。
・https://en.cppreference.com/w/cpp/language/initializer_list.html?utm_source=chatgpt.com
・https://en.cppreference.com/w/cpp/utility/initializer_list.html?utm_source=chatgpt.com
| for (int i = 0; i < static_cast<int>(nums.size()); ++i) { | ||
| int complement = target - nums[i]; | ||
| auto it = num_to_index.find(complement); | ||
| if (it != num_to_index.end()) { |
There was a problem hiding this comment.
C++20以降であれば、
num_to_index.contains(complement)
とした方が実際のコードの目的と合っているので読みやすいかと思います。
https://cpprefjp.github.io/reference/unordered_map/unordered_map/contains.html
There was a problem hiding this comment.
@ntanaka1984
コメントありがとうございます。
本当ですね。改めて確認しておきます。
|
|
||
| class Solution { | ||
| public: | ||
| std::vector<int> twoSum(std::vector<int>& nums, int target) { |
This problem: https://leetcode.com/problems/two-sum/
Next: https://leetcode.com/problems/group-anagrams/description/