diff --git a/300/step1.cpp b/300/step1.cpp new file mode 100644 index 0000000..2ea4da7 --- /dev/null +++ b/300/step1.cpp @@ -0,0 +1,29 @@ +/* +13:25 + +Time: O(n^2) +Space : O(n) + +ひとまず愚直に解く +対象のインデックスに到達するまでの最大長を保持し、その情報を後続で使用する + +*/ + +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector counts(nums.size(), 1); + for (int i = 1; i < nums.size(); ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + counts[i] = max(counts[j] + 1, counts[i]); + } + } + } + int max_count = 0; + for (int i = 0; i < counts.size(); ++i) { + max_count = max(counts[i], max_count); + } + return max_count; + } +}; diff --git a/300/step2.cpp b/300/step2.cpp new file mode 100644 index 0000000..db9c106 --- /dev/null +++ b/300/step2.cpp @@ -0,0 +1,27 @@ +/* + +Space: O(n) +Time: O(n log n) + +step1の改良 +もとの配列を同じ大きさを保持する必要はなく、配列長そのもので最大数を保持する。 +特定のインデックスの数値を小さくできると、後続でそこを経由して最大長を更新できる場合があるため更新する。 + +*/ + +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector num_to_count; + for (int i = 0; i < nums.size(); ++i) { + auto it = lower_bound(num_to_count.begin(), num_to_count.end(), nums[i]); + if (it == num_to_count.end()) { + num_to_count.push_back(nums[i]); + } else { + *it = nums[i]; + } + } + return num_to_count.size(); + + } +}; diff --git a/300/step3.cpp b/300/step3.cpp new file mode 100644 index 0000000..39c8601 --- /dev/null +++ b/300/step3.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector increasing_sequence; + for (auto num: nums) { + auto it = lower_bound(increasing_sequence.begin(), increasing_sequence.end(), num); + if (it == increasing_sequence.end()) { + increasing_sequence.push_back(num); + } else { + *it = num; + } + } + return increasing_sequence.size(); + } +};