300. Longest Increasing Subsequence#29
Conversation
| class Solution { | ||
| public: | ||
| int lengthOfLIS(vector<int>& nums) { | ||
| map<int, int> val_and_length; |
There was a problem hiding this comment.
map 型の変数については、 (キー)_to_(値) という命名をよく目にします。
There was a problem hiding this comment.
そうですね、andよりもtoの方がよさそうです。
| int max_length = 1; | ||
| for (int i = 0; i < nums.size(); i++) { | ||
| val_and_length[nums[i]] = max(1, val_and_length[nums[i]]); | ||
| for (auto it = val_and_length.begin(); it != val_and_length.end(); it++) { |
There was a problem hiding this comment.
ループ内で *it 以外で it を直接使用している箇所がないため、 ranged for 文で書いたほうがシンプルになると思います。
for (auto [val, length] : val_and_length) {There was a problem hiding this comment.
そうですね、そちらの方がシンプルそうです。ご指摘ありがとうございます。
| @@ -0,0 +1,12 @@ | |||
| ### step1 | |||
|
|
|||
| O(N ^ 2)の動的計画法しか思いつかなかった。 | |||
There was a problem hiding this comment.
ループの最内周で map にアクセスしているため、 O(N2 log N) のように思いました。
There was a problem hiding this comment.
そうですね、O(N2 log N) 掛かっていそうです。
| class Solution { | ||
| public: | ||
| int lengthOfLIS(vector<int>& nums) { | ||
| vector<int> length_and_val; |
There was a problem hiding this comment.
val だけですと、中に含まれている値がどのようなものか、分かりにくいように感じました。自分なら、 length_to_min_tail_val とすると思います。
There was a problem hiding this comment.
そうですね、そちらの方がわかりやすそうです。
| } | ||
| return max_length; | ||
| } | ||
| }; |
There was a problem hiding this comment.
map の代わりに nums と同じ要素数の vector でも同じことができると思いました。
vector を使うと時間計算量が O(N^2) になります。
この問題:https://leetcode.com/problems/longest-increasing-subsequence/description/
次に解く問題:https://leetcode.com/problems/maximum-subarray/description/