diff --git a/16-30/22.Search-Insert-Position/1.cpp b/16-30/22.Search-Insert-Position/1.cpp new file mode 100644 index 0000000..f24fa6a --- /dev/null +++ b/16-30/22.Search-Insert-Position/1.cpp @@ -0,0 +1,34 @@ +#if __has_include("../../debug.hpp") +#include "../../debug.hpp" +#endif +// ここまでローカルでのデバッグ用なので気にしないでください -------------------- + +#include + +using namespace std; + +// <時間> +// 6分 +// <感想> +// 直前に他の2分探索の問題を解いていたのですぐ解けるかと思っていたら +// (最初の早期リターンで)バグってしまった。まだまだ書き慣れていないみたい +// 書いてみて思ったが条件式はnums[mid]>=targetの方が分かりやすいかもしれない +// <他の人のコードを読んでコメント> +// - なるほど…、right=nums.size()とすること(半開区間)で最初の早期リターンを +// しなくてよくなるのか。色んなパターンがあるなあ。 +class Solution { + public: + int searchInsert(vector& nums, int target) { + if (nums.back() < target) return nums.size(); + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = (left + right) / 2; + if (nums[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } +}; diff --git a/16-30/22.Search-Insert-Position/1r.cpp b/16-30/22.Search-Insert-Position/1r.cpp new file mode 100644 index 0000000..d500e11 --- /dev/null +++ b/16-30/22.Search-Insert-Position/1r.cpp @@ -0,0 +1,28 @@ +#if __has_include("../../debug.hpp") +#include "../../debug.hpp" +#endif +// ここまでローカルでのデバッグ用なので気にしないでください -------------------- + +#include + +using namespace std; + +// <時間> +// 1分 +// <感想> +// 半開区間を意識したので条件式はnums[mid]& nums, int target) { + int left = 0, right = nums.size(); + while (left < right) { + int mid = (left + right) / 2; + if (nums[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return right; + } +}; diff --git a/16-30/22.Search-Insert-Position/README.md b/16-30/22.Search-Insert-Position/README.md new file mode 100644 index 0000000..f4e4c87 --- /dev/null +++ b/16-30/22.Search-Insert-Position/README.md @@ -0,0 +1,3 @@ +# 35.Search-Insert-Position + +