美文网首页
154. Find Minimum in Rotated Sor

154. Find Minimum in Rotated Sor

作者: juexin | 来源:发表于2017-01-09 19:24 被阅读0次

    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.

    public class Solution {
        public int findMin(int[] nums) {
            
            int start = 0,end = nums.length-1;
            while(nums[start]>=nums[end])   //  注意限制条件!!!
            {
                int mid = (start + end)>>1;
                System.out.println(nums[mid]);
                System.out.println(nums[start]);
                if(nums[mid]==nums[start]&&nums[mid]==nums[end])
                {
                    int min = nums[0];
                    for(int i=1;i<nums.length;i++)
                    {
                        if(nums[i]<min)
                           min = nums[i];
                    }
                    return min;
                }
                if(nums[mid]>=nums[start])
                   {
                       start = mid +1;
                       System.out.println(start);
                   }
                else 
                   {
                       end = mid;
                  //     System.out.println(end);
                   }
            }
            return nums[start];//注意这个神奇的start或者left!!!
        }
    }
    

    相关文章

      网友评论

          本文标题:154. Find Minimum in Rotated Sor

          本文链接:https://www.haomeiwen.com/subject/yaphbttx.html