154. Find Minimum in Rotated Sorted Array II
题目:
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Find the minimum element.
The array may contain duplicates.
链接:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/#/description
5/2/2017
有duplicate,O(N)时间复杂度
1 public class Solution { 2 public int findMin(int[] nums) { 3 if (nums == null || nums.length == 0) { 4 return -1; 5 } 6 for (int i = 1; i < nums.length; i++) { 7 if (nums[i] < nums[i - 1]) { 8 return nums[i]; 9 } 10 } 11 return nums[0]; 12 } 13 }
别人的答案
只让mid与end比较,但是时间复杂度还是O(N)
https://discuss.leetcode.com/topic/6468/my-pretty-simple-code-to-solve-it
1 class Solution { 2 public: 3 int findMin(vector<int> &num) { 4 int lo = 0; 5 int hi = num.size() - 1; 6 int mid = 0; 7 8 while(lo < hi) { 9 mid = lo + (hi - lo) / 2; 10 11 if (num[mid] > num[hi]) { 12 lo = mid + 1; 13 } 14 else if (num[mid] < num[hi]) { 15 hi = mid; 16 } 17 else { // when num[mid] and num[hi] are same 18 hi--; 19 } 20 } 21 return num[lo]; 22 } 23 };
更多讨论:
https://discuss.leetcode.com/category/162/find-minimum-in-rotated-sorted-array-ii