LeetCode OJ 154. Find Minimum in Rotated Sorted Array II
Posted Black_Knight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 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 a sorted array 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.
【题目分析】
与Find Minimum in Rotated Sorted Array题目相比,这个题目中数组元素可能是重复的。
【思路】
【java代码】非递归
1 public class Solution { 2 public int findMin(int[] nums) { 3 int start=0,mid=0,end=nums.length-1; 4 while(start<end){ 5 if(nums[start] < nums[end]) return nums[start]; 6 7 mid=start+(end-start)/2; 8 if(nums[mid]>nums[end]) start=mid+1; 9 else if(nums[mid]==nums[end]) end--; 10 else end=mid; 11 } 12 return nums[start]; 13 } 14 }
1 public class Solution { 2 public int findMin(int[] nums) { 3 int len = nums.length; 4 if(len == 1) return nums[0]; 5 6 return find(nums, 0, len-1); 7 } 8 9 public int find(int nums[], int left, int right){ 10 while(left < right){ 11 if(nums[left] < nums[right]) return nums[left]; 12 if(left == right - 1) return Math.min(nums[left], nums[right]); 13 14 int mid = left + (right - left)/2; 15 if(nums[left] == nums[mid] && nums[mid] == nums[right]) 16 return Math.min(find(nums, left, mid-1), find(nums, mid+1, right)); 17 18 if(nums[left] <= nums[mid]) left = mid + 1; 19 else right = mid; 20 } 21 return nums[left]; 22 } 23 }
以上是关于LeetCode OJ 154. Find Minimum in Rotated Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 154. Find Minimum in Rotated Sorted Array II
LeetCode 154.Find Minimum in Rotated Sorted Array II
leetcode 154. Find Minimum in Rotated Sorted Array II --------- java
Leetcode.154.Find Minimum in Rotated Sorted Array II
leetcode-Find Minimum in Rotated Sorted Array II-154
[LeetCode] 154. Find Minimum in Rotated Sorted Array II 寻找旋转有序数组的最小值 II