[LeetCode] 153. Find Minimum in Rotated Sorted Array 寻找旋转有序数组的最小值

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.

You may assume no duplicate exists in the array.

解法1: Brute Force,直接迭代搜索。 T:O(n)

解法1: 二分法,Binary Search, T:O(logn)

显然二分法是要考察的,至于旋转数组的二分法与33. Search in Rotated Sorted Array类似。

 

Python:

class Solution(object):
    def findMin(self, nums):
        left, right = 0, len(nums)
        target = nums[-1]

        while left < right:
            mid = left + (right - left) / 2

            if nums[mid] <= target:
                right = mid
            else:
                left = mid + 1

        return nums[left]

Python:

class Solution2(object):
    def findMin(self, nums):
        left, right = 0, len(nums) - 1
        while left < right and nums[left] >= nums[right]:
            mid = left + (right - left) / 2

            if nums[mid] < nums[left]:
                right = mid
            else:
                left = mid + 1

        return nums[left]

C++:

class Solution {
public:
    int findMin(vector<int> &num) {
        int left = 0, right = num.size() - 1;
        if (num[left] > num[right]) {
            while (left != (right - 1)) {
                int mid = (left + right) / 2;
                if (num[left] < num[mid]) left = mid;
                else right = mid;
            }
            return min(num[left], num[right]);
        }
        return num[0];
    }
};

 

类似题目:

[LeetCode] 33. Search in Rotated Sorted Array 在旋转有序数组中搜索

[LeetCode] 81. Search in Rotated Sorted Array II 在旋转有序数组中搜索 II

[LeetCode] 154. Find Minimum in Rotated Sorted Array II 寻找旋转有序数组的最小值 II
 

All LeetCode Questions List 题目汇总

 

posted @ 2018-03-10 08:39  轻风舞动  阅读(393)  评论(0编辑  收藏  举报