Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0db06f9

Browse files
authored
Merge pull requestneetcode-gh#1091 from sidhant-khamankar/patch-2
Solution as discussed in video at neetcode channel
2 parents4bc2fcf +5301655 commit0db06f9

File tree

1 file changed

+33
-28
lines changed

1 file changed

+33
-28
lines changed
Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,41 @@
11
/*
2-
Given sorted array after some rotation, find min value
3-
Ex. nums = [3,4,5,1,2] -> 1, nums = [4,5,6,7,0,1,2] -> 0
2+
* @lc app=leetcode id=153 lang=cpp
3+
*
4+
* [153] Find Minimum in Rotated Sorted Array
5+
*/
46

5-
Binary search + ensuring we never disqualify possible min value
7+
// @lc code=start
8+
classSolution
9+
{
10+
public:
11+
intfindMin(vector<int> &nums)
12+
{
13+
// Neetcode solution Ologn time O1 space binary search
14+
int res = nums[0];
15+
int l =0;
16+
int r = nums.size() -1;
617

7-
Time: O(log n)
8-
Space: O(1)
9-
*/
18+
while (l <= r)
19+
{
20+
if (nums[l] < nums[r])
21+
{
22+
res =min(res, nums[l]);
23+
break;
24+
}
25+
int mid = l + (r - l) /2;
26+
res =min(res, nums[mid]);
1027

11-
classSolution {
12-
public:
13-
intfindMin(vector<int>& nums) {
14-
int low =0;
15-
int high = nums.size() -1;
16-
17-
// not low <= high since not searching for target
18-
while (low < high) {
19-
int mid = low + (high - low) /2;
20-
// ex. [3,4,5,6,7,8,9,1,2], mid = 4, high = 8
21-
// nums[mid] > nums[high], min must be right
22-
if (nums[mid] > nums[high]) {
23-
// never consider mid bc know for sure not min
24-
low = mid +1;
25-
// ex. [8,9,1,2,3,4,5,6,7], mid = 4, high = 8
26-
// nums[mid] <= nums[right], min must be left
27-
}else {
28-
// consider mid still bc could be min
29-
high = mid;
28+
if (nums[mid] >= nums[l])// mid present in left sorted array
29+
{
30+
l = mid +1;// try to move closer to right sorted array
31+
}
32+
else
33+
{
34+
r = mid -1;
3035
}
3136
}
32-
33-
// low lands on correct value, never disqualified mins
34-
return nums[low];
37+
38+
return res;
3539
}
3640
};
41+
// @lc code=end

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp