LeetCode154——尋找旋轉排序陣列中的最小值 II
阿新 • • 發佈:2019-01-12
我的LeetCode程式碼倉:https://github.com/617076674/LeetCode
原題連結:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/description/
題目描述:
知識點:二分查詢法
思路一:暴力破解法
本題是LeetCode153——尋找旋轉排序陣列中的最小值的加強版,但對於暴力破解法而言,和LeetCode153——尋找旋轉排序陣列中的最小值無任何差別。
時間複雜度是O(n),其中n為陣列中的元素個數。空間複雜度是O(1)。
JAVA程式碼:
public class Solution { public int findMin(int[] nums) { int result = Integer.MAX_VALUE; for (int i = 0; i < nums.length; i++) { if(nums[i] < result){ result = nums[i]; } } return result; } }
LeetCode解題報告:
思路二:二分查詢法
和LeetCode153——尋找旋轉排序陣列中的最小值的思路二相比,由於本題可能存在重複的元素,我們需要用一個int型變數result來儲存當前已得到的陣列中的最小值,基本實現和LeetCode153——尋找旋轉排序陣列中的最小值的思路二相同。
時間複雜度是O(logn),其中n為陣列中的元素個數。空間複雜度是O(1)。
JAVA程式碼:
class Solution { public int findMin(int[] nums) { int left = 0, right = nums.length - 1; int result = Integer.MAX_VALUE; while (left < right) { if (right - left == 1) { return Math.min(result, Math.min(nums[left], nums[right])); } int mid = left + (right - left) / 2; if (nums[left] < nums[right]) { return Math.min(result, nums[left]); } else if (nums[left] == nums[right]) { result = Math.min(result, nums[left]); left++; right--; } else { if (nums[left] <= nums[mid]) { left = mid; } else { right = mid; } } } return Math.min(result, nums[left]); } }
LeetCode解題報告: