From a5b87f9b7052f9d2283465fae18b75e314dc868c Mon Sep 17 00:00:00 2001 From: potrue <126231160+potrue@users.noreply.github.com> Date: Mon, 11 Aug 2025 17:26:20 +0900 Subject: [PATCH] 33. Search in Rotated Sorted Array https://leetcode.com/problems/search-in-rotated-sorted-array/description/ --- 33/33.md | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 33/33.md diff --git a/33/33.md b/33/33.md new file mode 100644 index 0000000..0589037 --- /dev/null +++ b/33/33.md @@ -0,0 +1,97 @@ +## 何も見ずに解いてみる + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + int left = 0; + int right = nums.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + return mid; + } + if (nums[mid] < nums[right]) { + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; + } + else { + right = mid - 1; + } + } + else { + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; + } + else { + left = mid + 1; + } + } + } + return -1; + } +}; +``` + +## 他の人のコードを見てみる + +https://github.com/tokuhirat/LeetCode/pull/43/files +https://github.com/ryosuketc/leetcode_arai60/pull/32/files +https://github.com/Ryotaro25/leetcode_first60/pull/47/files + +一回最小値を見つけてから普通の二分探索でやるという選択肢もあるが、一個前の問題(153. Find Minimum in Rotated Sorted Array)のことを忘れたとしてその発想で解くのが自然かといわれると微妙な気もする。 + +std::partition_pointで書いてみた。意外と悪くないかも? + +```cpp +class Solution { +public: + int search(std::vector& nums, int target) { + auto it = std::partition_point(nums.begin(), nums.end(), [&nums, target](int x){ + return (target >= nums.front() && (x >= nums.front() && x < target)) || + (target < nums.front() && (x >= nums.front() || x < target)); + }); + if (it != nums.end() && *it == target) { + return std::distance(nums.begin(), it); + } + return -1; + } +}; +``` + +## 最終コード + +std::partition_pointの解法と迷ったがとりあえずオーソドックスなやり方で + +```cpp +class Solution { +public: + int search(vector& nums, int target) { + int left = 0; + int right = nums.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + return mid; + } + if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; + } + else { + left = mid + 1; + } + } + else { + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; + } + else { + right = mid - 1; + } + } + } + return -1; + } +}; +```