153 Find Minimum in Rotated Sorted Array

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了153 Find Minimum in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。

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.

You may assume no duplicate exists in the array.

=========

解决思路:

/**
012 3 4567
701 2 3456
670 2345
567 0 1234
456 7 0123
345 6 7012
234 5 6701
123 4 5670
*/

解决方式:利用二分搜索  去掉数组左右两部分中有序的部分。

mid =( left+right)/2;

mark表示最小值的下标,初始值为mark =right

mid将nums分为左右两个部分,因为数组中没有重复元素,

当nums[mid]<nums[right]时,数组右边部分有序,

  判断数组右边有序部分的最小值,是不是nums[mark]小

  此时数组右边已经搜索过了,应该在数组左边搜索,所以right = mid-1;

当nums[mid]>nums[right],数组左边部分有序,

  判断数组左边有序部分的最小值,是不是比nums[mark]小,更新mark值[这里在代码里存在异议???和mark]

  此时数组左边以及搜索过了,应该在数组右边搜索,所以left = mid+1;

 

int findMin(vector<int>& nums) {
        if(nums.size()==0)return 0;
        int left = 0;
        int right = nums.size()-1;
        int mark = right;
        while(left<=right){
            if(left+1==right){
                mark = nums[left]<nums[mark]?left:mark;
                mark = nums[right]<nums[mark]?right:mark;
                break;
            }
            int mid = (left+right)/2;
            if(nums[mid]<nums[right]){
                if(nums[mid]<nums[mark])
                    mark = mid;
                right = mid-1;
            }else{
                if(nums[left]<nums[mark])
                    mark = mid;
                left = mid+1;
            }
        }///while
        return nums[mark];
    }

 

以上是关于153 Find Minimum in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

153. Find Minimum in Rotated Sorted Array

#Leetcode# 153. Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array

153 Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array