Conversation
| for (int i = 0; i < nums.size(); i++) { | ||
| int complement = target - nums[i]; | ||
| if (num_to_index.contains(complement)) { | ||
| vector<int> ans = {i, num_to_index[complement]}; |
There was a problem hiding this comment.
以下のように直接returnをかけるので、ansのような一次変数におく必要はないと思います。
return {i, num_to_index[complement]};There was a problem hiding this comment.
レビューありがとうございます。
なるほど、なぜか3msから変わらないと思っていたらこの変数がボトルネックになっていました。
ご指摘助かりました。
There was a problem hiding this comment.
コンパイラでおそらく最適化されますし、これがボトルネックになることはないと思います。実行時間のブレは、LeetCodeの環境によるものかと思われます。
| public: | ||
| vector<int> twoSum(vector<int>& nums, int target) { | ||
| int i, j; | ||
| for (i = 0; i <= (nums.size() - 1); i++) { |
There was a problem hiding this comment.
この(nums.size() - 1)で、外側のかっこが無いほうが見慣れた感じで好みです。
There was a problem hiding this comment.
レビューありがとうございます。
理解不足で括弧必要だと勘違いしていました。
i < nums.size()でもいけますね。
There was a problem hiding this comment.
演算子の優先順位で調べてみると良いと思います。自明ではないなら、不要でも括弧をつけるのもありですね。
https://en.cppreference.com/cpp/language/operator_precedence
| vector<int> ans = {i, num_to_index[complement]}; | ||
| return ans; | ||
| } | ||
| else { |
There was a problem hiding this comment.
ifの中で returnしているので、このelseを消してインデントを下げられますね。どちらでも趣味の範囲だと思います。
| class Solution { | ||
| public: | ||
| vector<int> twoSum(vector<int>& nums, int target) { | ||
| int i, j; |
There was a problem hiding this comment.
for (int i = 0; i <= (nums.size() - 1); i++)のように使う直前に宣言すると良いと思います。
|
|
||
| ## step2 | ||
| leetcodeの解法見た。unordered_mapをsum_to_pairでなくnum_to_indexで作る。 | ||
| targer-nums[i] をnum_to_indexで検索すると一瞬で答えがわかる。 |
There was a problem hiding this comment.
Hash tableの仕組み(衝突回避やリアロケーションなど)についても、まだ調べていなかったら見てみると良いと思います。
https://en.wikipedia.org/wiki/Hash_table
There was a problem hiding this comment.
レビューありがとうございます。
ハッシュテーブルの仕組みについては調べていなかったのでリンク参考になります。
挙げていただいた論点についても調べてみます。
|
|
||
| arai60の分類だとhashmapに該当するのだが、どこでmapを使うべきかわからなかった。 | ||
| 今までの問題だとsum_to_pairのmapを作ることが多かった。 | ||
| 前回の問題でも(https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) 、そのようなsum_to_pairで全走査する方式を使って上手くいかなかったが思いつかなかったので今回も全走査した。 |
There was a problem hiding this comment.
こちらのことでしょうか?そうでしたら、mapではなくて、pairですね。
https://github.com/nicah4o/arai60/pull/10/files#diff-4441ba9bfe4587a375388da6cd11a2db15081cba994b37ca9f2ec8fddf3b327eR22-R23
using pi = pair<int, vector<int>>;
priority_queue<pi, vector<pi>, greater<pi>> sum_to_pair;
This problem; https://leetcode.com/problems/two-sum/description/
Next problem: https://leetcode.com/problems/group-anagrams/description/