You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When an array is given, that is sorted in ascending order.
But it is rotated 1~n times.
When array is [0,1,2,4,5,6,7]
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Approach
First, find out it is rotated or not.
If it rotated n times that is its length, it is same as default.
Then, find out which part the initial value exist by comparing mid value of array with start value of array.
It can be in left part or right part.
The code is below.
/** * [0,1,2,3,4,5,6,7] not rotated * [7,0,1,2,3,4,5,6] rotated && nums[mid] < nums[0] Then MIN is in the LEFT-SIDE * [6,7,0,1,2,3,4,5] rotated && nums[mid] < nums[0] Then MIN is in the LEFT-SIDE * [5,6,7,0,1,2,3,4] rotated && nums[mid] < nums[0] Then MIN is in the LEFT-SIDE * [4,5,6,7,0,1,2,3] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE * [3,4,5,6,7,0,1,2] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE * [2,3,4,5,6,7,0,1] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE * [1,2,3,4,5,6,7,0] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE * [0,1,2,3,4,5,6,7] not rotated * * [3,4,5,6,7,0,1,2] rotated, nums[mid] >= nums[0] MIN is in the RIGHT-SIDE * [7,0,1,2] rotated, nums[mid] < nums[0] MIN is in the LEFT-SIDE * [7,0] rotated, nums[mid] >= nums[0] MIN is in the RIGHT-SIDE * [0] MIN detected. * * [4,5,6,7,0,1,2,3] rotated nums[mid] >= nums[0] MIN is in the RIGHT-SIDE * [0,1,2,3] is not rotated, return nums[0]; * * [2,3,4,5,6,7,0,1] rotated nums[mid] >= nums[0] MIN is in the RIGHT-SIDE * [6,7,0,1] rotated, nums[mid] >= nums[0] MIN is in the RIGHT-SIDE * [0,1] not rotated, return nums[0]; */functionfindMinValue(nums,s,e){// If not rotatedif(nums[s]<nums[e]||s===e)returnnums[s];// If rotated.constmid=(s+e)>>1;// Min value is in the left-side.if(nums[mid]<nums[s]){returnfindMinValue(nums,s,mid);}// Min value is in the right-side.else{returnfindMinValue(nums,mid+1,e);}}
The text was updated successfully, but these errors were encountered:
Problem
When an array is given, that is sorted in ascending order.
But it is rotated 1~n times.
Approach
First, find out it is rotated or not.
If it rotated n times that is its length, it is same as default.
Then, find out which part the initial value exist by comparing mid value of array with start value of array.
It can be in left part or right part.
The code is below.
The text was updated successfully, but these errors were encountered: