forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solution as discussed in video at neetcode channel
- Loading branch information
1 parent
fb55f39
commit 5301655
Showing
1 changed file
with
33 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,36 +1,41 @@ | ||
/* | ||
Given sorted array after some rotation, find min value | ||
Ex. nums = [3,4,5,1,2] -> 1, nums = [4,5,6,7,0,1,2] -> 0 | ||
* @lc app=leetcode id=153 lang=cpp | ||
* | ||
* [153] Find Minimum in Rotated Sorted Array | ||
*/ | ||
|
||
Binary search + ensuring we never disqualify possible min value | ||
// @lc code=start | ||
class Solution | ||
{ | ||
public: | ||
int findMin(vector<int> &nums) | ||
{ | ||
// Neetcode solution Ologn time O1 space binary search | ||
int res = nums[0]; | ||
int l = 0; | ||
int r = nums.size() - 1; | ||
|
||
Time: O(log n) | ||
Space: O(1) | ||
*/ | ||
while (l <= r) | ||
{ | ||
if (nums[l] < nums[r]) | ||
{ | ||
res = min(res, nums[l]); | ||
break; | ||
} | ||
int mid = l + (r - l) / 2; | ||
res = min(res, nums[mid]); | ||
|
||
class Solution { | ||
public: | ||
int findMin(vector<int>& nums) { | ||
int low = 0; | ||
int high = nums.size() - 1; | ||
|
||
// not low <= high since not searching for target | ||
while (low < high) { | ||
int mid = low + (high - low) / 2; | ||
// ex. [3,4,5,6,7,8,9,1,2], mid = 4, high = 8 | ||
// nums[mid] > nums[high], min must be right | ||
if (nums[mid] > nums[high]) { | ||
// never consider mid bc know for sure not min | ||
low = mid + 1; | ||
// ex. [8,9,1,2,3,4,5,6,7], mid = 4, high = 8 | ||
// nums[mid] <= nums[right], min must be left | ||
} else { | ||
// consider mid still bc could be min | ||
high = mid; | ||
if (nums[mid] >= nums[l]) // mid present in left sorted array | ||
{ | ||
l = mid + 1; // try to move closer to right sorted array | ||
} | ||
else | ||
{ | ||
r = mid - 1; | ||
} | ||
} | ||
|
||
// low lands on correct value, never disqualified mins | ||
return nums[low]; | ||
|
||
return res; | ||
} | ||
}; | ||
// @lc code=end |