1. Two Sum#10
Conversation
| class Solution { | ||
| public: | ||
| std::vector<int> twoSum(std::vector<int>& nums, int target) { | ||
| std::vector<std::pair<int, int>> nums_with_index; |
There was a problem hiding this comment.
index は単数形ですし、実際入っているのは単数の num なので、num_with_index とか num_and_index の方が自然なように思います。
There was a problem hiding this comment.
今までに見た数を set で管理して complement と比較するようなアプローチは言及があってもよいかと思いました。
There was a problem hiding this comment.
ありがとうございます。先にソートしなくてよい分早く見つかればそちらのほうがはやいですね!(追加しました。)
| std::sort(nums_with_index.begin(), nums_with_index.end()); | ||
|
|
||
| for (int i = 0; i < nums_with_index.size(); ++i) { | ||
| auto compare_num = [](const auto& a, const auto& b) { return a.first < b.first; }; |
There was a problem hiding this comment.
std::pair::operator<() で代用できるため、比較関数を自前で実装する必要はないと思います。
There was a problem hiding this comment.
ありがとうございます。pairの比較の仕方を考えればおっしゃる通りでした。
| const auto complement = std::make_pair(target - nums_with_index[i].first, -1); | ||
| auto it = std::lower_bound(nums_with_index.begin() + i + 1, nums_with_index.end(), complement, compare_num); | ||
| if (it != nums_with_index.end() && (*it).first == complement.first) { | ||
| return std::vector<int>{nums_with_index[i].second, (*it).second}; |
There was a problem hiding this comment.
戻り値が std::vector のため、
return {nums_with_index[i].second, (*it).second};と書けば十分だと思います。
| // numの比較しかしないのでindexはdummy | ||
| const auto complement = std::make_pair(target - nums_with_index[i].first, -1); | ||
| auto it = std::lower_bound(nums_with_index.begin() + i + 1, nums_with_index.end(), complement, compare_num); | ||
| if (it != nums_with_index.end() && (*it).first == complement.first) { |
| for (int i = 0; i < nums.size(); ++i) { | ||
| auto complement = seen_num_to_index.find(target - nums[i]); | ||
| if (complement != seen_num_to_index.end()) { | ||
| two_indices = {i, complement->second}; |
There was a problem hiding this comment.
return {i, complement->second}; したほうがシンプルだと思います。
There was a problem hiding this comment.
ここでreturnしてしまうと、step1のように正しい入力の場合到達しない部分で不自然なコードを返すことになるのを避けたいという気持ちからでした。今見返すと、不正な入力にタイしては最後に要素数0のvectorを返すのが分かりやすく思います。
| @@ -0,0 +1,156 @@ | |||
| # step1 | |||
| - 愚直にやると二重ループだが何度も同じ値を参照することになり無駄が多い(時間計算量O(n^2)) | |||
| - 小さい順に並べておくと、一つ固定した下で対となりうる値はそれより後ろにしかなく二分探索で見つけられる。 | |||
This Problem
https://leetcode.com/problems/two-sum/