首页 > 代码库 > leetcode之Search in Rotated Sorted Array,剑指offer之旋转数组的最小数字

leetcode之Search in Rotated Sorted Array,剑指offer之旋转数组的最小数字

Search 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).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

class Solution {
public:
    int search(int A[], int n, int target) {
    	int left = 0,right = n-1;
    	while(left <= right)
    	{
    		int mid = left + ((right-left)>>1);
    		if(A[mid] == target)return mid;
    		if(A[mid] > A[right])//第一段递增区间
    		{
    			if(A[left] <= target && target < A[mid])right = mid-1;
    			else left = mid + 1;
    		}
    		else //第二段递增区间
    		{
    			if(A[mid] < target && target <= A[right])left = mid+1;
    			else right = mid - 1;
    		}
    	}
    	return -1;
    }
};

Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

class Solution {
public:
    bool search(int A[], int n, int target) {
    	int left = 0,right = n-1;
    	while(left <= right)
    	{
    		int mid = left + ((right-left)>>1);
    		if(A[mid] == target)return true;
    		if(A[mid] == A[right])//遍历最后一段
    		{
    			for(;right >= mid;--right)
    			{
    				if(A[right] == target)return true;
    			}
    		}
    		else if(A[mid] > A[right])//第一段递增区间
    		{
    			if(A[left] <= target && target < A[mid])right = mid-1;
    			else left = mid + 1;
    		}
    		else //第二段递增区间
    		{
    			if(A[mid] < target && target <= A[right])left = mid + 1;
    			else right = mid - 1;
    		}
    	}
    	return false;
    }
};

剑指offer:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。

思路:这里给出和上面两个类似的思路,和剑指offer上的不太一样,我觉得剑指offer上的不好理解,但是这个算法的效率没有书上的高,九度空间上超时了。

int RotateArray(int* data,int n)
{
	int left = 0,right = n-1,minValue = http://www.mamicode.com/INT_MAX;>


leetcode之Search in Rotated Sorted Array,剑指offer之旋转数组的最小数字