【第22期】观点:IT 行业加班,到底有没有价值?

LeetCode-153.Find Minimum in Rotated Sorted Array

原创 2016年05月31日 12:41:39

https://leetcode.com/problems/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.

二分查找

如果nums[start] < nums[end],那就已经有序了

public int FindMin(int[] nums) 
    {
        int start = 0, end = nums.Length - 1, mid;
        if (end == 0)
            return nums[0];
        while (start+1!=end)
        {
            if (nums[start] < nums[end])
                return nums[start];
            mid = (start + end) / 2;
            if (nums[start] < nums[mid])
                start = mid;
            else
                end = mid;
        }
        return Math.Min(nums[start], nums[end]);
    }

int findMin(vector<int>& nums) 
    {
        int l = 0, r = nums.size() - 1, mid;
    	while (l < r)
    	{
    	    if (nums[l] < nums[r])
			break;
    		mid = l + (r - l) / 2;
    		if (nums[mid] >= nums[l])
    			l = mid + 1;
    		else
    			r = mid;
    	}
    	return nums[l];
    }

如果存在重复数字,如1 0 1 1 1
则mid=2时,无法判定nums[mid]属于哪一边,因此只能顺序查找。参考《剑指Offer》P69
int helper(vector<int> &nums, int l, int r)
{
	int res = nums[l];
	for (int i = l + 1; i <= r; i++)
		res = min(res, nums[i]);
	return res;
}

int findMin(vector<int> nums)
{
	int l = 0, r = nums.size() - 1, mid;
	while (l < r)
	{
		if (nums[l] < nums[r])
			break;
		mid = l + (r - l) / 2;

		if (nums[l] == nums[mid] && nums[r] == nums[mid])//如果三个值相等 只能顺序查找
			return helper(nums, l, r);

		if (nums[mid] >= nums[l])
			l = mid + 1;
		else
			r = mid;
	}
	return nums[l];
}


版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

leetcode解题之153&154. Find Minimum in Rotated Sorted Array版(在旋转的数组中查找最小数字)

leetcode解题之153&154. Find Minimum in Rotated Sorted Array版(在旋转的数组中查找最小数字)

[LeetCode]154.Find Minimum in Rotated Sorted Array II

【题目】 <blockquote style="padding: 10px 20px; margin: 0px 0px 20px; font-size: 17.5px; border-left-width: 5px; border-left-style: solid; border-left-color: rgb(238,238,238); color: rgb(51,51,51); font-family: 'Helvetica Neue',Helvetica,Arial,sans

[LeetCode]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 ...

[LeetCode]153.Find Minimum in Rotated Sorted Array

【题目】 Suppose a sorted array is rotated at some pivot unknown to you beforehan

Leetcode 153. Find Minimum in Rotated Sorted Array (Medium) (cpp)

Leetcode 153. Find Minimum in Rotated Sorted Array (Medium) (cpp)
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)