Leetcode: 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.

思路:①最原始的遍历一遍数组就好了;②二分查找,能减少算法的复杂度。

C++代码一(老老实实遍历一遍数组数据):

class Solution
{
public:
    int findMin(vector<int> &num)
    {
        for (size_t i = 1; i < num.size(); i++)
        {
            if (num[i - 1] > num[i]) return num[i];
        }
        return num[0];
    }
};

C++代码二(二分查找):

class Solution
{
public:
    int findMin(vector<int> &num)
    {
        size_t size = num.size() - 1;
        int left = 0;
        int right = int(size);
        int middle = right / 2;
        //注意这里循环条件有等号
        while(left <= right)
        {
            middle = (left+ right) / 2;
            //如果middle比最后一个数字大,说明最小值在右边,反之,最小值在左边
            if (num[middle] > num[size]) left = middle + 1;
            else right = middle - 1;
        }
        return num[left];
    }
};

C++代码三(对middle的求法和二不同):

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

C++代码四(right的求法和二不同,注意while循环条件也会不同):

class Solution
{
public:
    int findMin(vector<int> &num)
    {
        size_t size = num.size() - 1;
        int left = 0;
        int right = int(size);
        int middle = right / 2;
        //这里循环条件不用等号
        while(left < right)
        {
            middle = (right + left) / 2;
            if (num[middle] > num[size]) left = middle + 1;
            else right = middle;
        }
        return num[left];
    }
};

C#代码:

public class Solution
{
    public int FindMin(int[] num) 
    {
        int size = num.Length - 1;
        int left = 0;
        int right = size;
        int middle = right / 2;
        while (left < right)
        {
            middle = (left + right) / 2;
            if (num[middle] > num[size]) left = middle + 1;
            else right = middle;
        }
        return num[right];
    }
}

Python代码:

class Solution:
    # @param num, a list of integer
    # @return an integer
    def findMin(self, num):
        size = len(num) - 1
        left = 0
        right = size
        middle = right / 2
        while left < right:
            middle = (left + right) /2
            if num[middle] > num[size]:
                left = middle + 1
            else:
                right = middle
        return num[left]

你可能感兴趣的:(LeetCode,sorted)