Leetcode 153. Find Minimum in Rotated Sorted Array
題目的意思是給定一個升序排列的陣列,該陣列在某一個點翻轉了,根據翻轉後的陣列求該陣列的最小值。
方法1:通過觀察,翻轉後的陣列,如果某一個數比前一個數小,那麼這個數就是陣列的最小值,遍歷該陣列找到最小值,時間複雜度O(n).
class Solution {
public:
int findMin(vector<int>& nums) {
int re=nums[0];
for(int i=0; i<nums.size()-1; ++i)
{
if(nums[i]>nums[i+1])
re=nums[i+1];
}
return re;
}
};
方法2:二分查詢法的變形。先判斷區間是否是單調遞增區間,也就是看l是否小於等於r,如果是的話,l就是所求。如果不是單調遞增區間,也就是l比r大:如果mid大於等於l,說明最小值落在右半部分;如果mid比l小,說明最小值落在左半部分,也可能最小值就是mid本身。時間複雜度O(logn)
class Solution {
public:
int findMin(vector<int>& nums) {
int l=0, r=nums.size()-1;
while(l<r && nums[l]>nums[r])
{
int mid=(l+r)/2;
if(nums[mid]>=nums[l])
l=mid+1;
else
r=mid;
}
return nums[l];
}
};
相關文章
- LeetCode | 153. Find Minimum in Rotated Sorted ArrayLeetCode
- Find Minimum in Rotated Sorted Array leetcode javaLeetCodeJava
- Leetcode-Find Minimum in Rotated Sorted ArrayLeetCode
- Leetcode-Find Minimum in Rotated Sorted Array IILeetCode
- [LeetCode] Find Minimum in Rotated Sorted Array (包含遞增和遞減旋轉)LeetCode
- Leetcode Search in Rotated Sorted ArrayLeetCode
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- Leetcode Search in Rotated Sorted Array IILeetCode
- Leetcode-Search in Rotated Sorted ArrayLeetCode
- Search in Rotated Sorted Array leetcode javaLeetCodeJava
- leetcode33_Search in Rotated Sorted ArrayLeetCode
- LeetCode-Search in Rotated Sorted Array IILeetCode
- Search in Rotated Sorted Array II leetcode javaLeetCodeJava
- Leetcode 34 Find First and Last Position of Element in Sorted ArrayLeetCodeAST
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- [LeetCode] Search in Rotated Sorted Array 在旋轉有序陣列中搜尋LeetCode陣列
- [LeetCode] 3011. Find if Array Can Be SortedLeetCode
- Leetcode Merge Sorted ArrayLeetCode
- leetcode Remove Duplicates from Sorted ArrayLeetCodeREM
- Leetcode-Merge Sorted ArrayLeetCode
- [CareerCup] 11.3 Search in Rotated Sorted Array 在旋轉有序矩陣中搜尋矩陣
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- Leetcode 26 Remove Duplicates from Sorted ArrayLeetCodeREM
- Leetcode 88. Merge Sorted ArrayLeetCode
- Leetcode Remove Duplicates from Sorted Array IILeetCodeREM
- Leetcode-Convert Sorted Array to BSTLeetCode
- Leetcode-Remove Duplicates from Sorted ArrayLeetCodeREM
- Median of Two Sorted Array leetcode javaLeetCodeJava
- Remove Duplicates from Sorted Array leetcode javaREMLeetCodeJava
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- 【Leetcode】453. Minimum Moves to Equal Array ElementsLeetCode
- Leetcode 453. Minimum Moves to Equal Array ElementsLeetCode
- [leetcode]remove-duplicates-from-sorted-array-iiLeetCodeREM
- Leetcode-Remove Duplicates from Sorted Array IILeetCodeREM
- Remove Duplicates from Sorted Array II leetcode javaREMLeetCodeJava
- Leetcode 442. Find All Duplicates in an ArrayLeetCode
- [leetcode] 1394. Find Lucky Integer in an ArrayLeetCode
- Leetcode Convert Sorted Array to Binary Search TreeLeetCode