diff --git a/Leetcode/34/ysuh/README.md b/Leetcode/34/ysuh/README.md new file mode 100644 index 0000000..726f807 --- /dev/null +++ b/Leetcode/34/ysuh/README.md @@ -0,0 +1,11 @@ +## Link +[Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/) + +## Topic +binary search + +## Approach +find the target via binary search +find the left and right via binary recursive search + +## Note diff --git a/Leetcode/34/ysuh/solution.cpp b/Leetcode/34/ysuh/solution.cpp new file mode 100644 index 0000000..5073011 --- /dev/null +++ b/Leetcode/34/ysuh/solution.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + vector binarySearch(vector& nums, int target, int start, int end) { + while (start <= end) { + int mid = (start + end) / 2; + if (nums[mid] == target) { + return {findLeft(nums, target, start, mid-1), findRight(nums, target, mid+1, end)}; + } else if (nums[mid] > target) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return {-1, -1}; + } + + int findLeft(vector& nums, int target, int start, int end) { + while (start <= end) { + int mid = (start + end) / 2; + if (nums[mid] == target) { + return findLeft(nums, target, start, mid-1); + } else if (nums[mid] > target) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return end + 1; + } + + int findRight(vector& nums, int target, int start, int end) { + while (start <= end) { + int mid = (start + end) / 2; + if (nums[mid] == target) { + return findRight(nums, target, mid+1, end); + } else if (nums[mid] > target) { + end = mid - 1; + } else { + start = mid + 1; + } + } + return start - 1; + } + + vector searchRange(vector& nums, int target) { + if (!nums.size()) return {-1, -1}; + return binarySearch(nums, target, 0, nums.size()-1); + } +};