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

题目大致的意思是有一个已经排好序的数组,现在把其中的元素按照某一个轴进行旋转,比如说0 1 2 4 5 6 7旋转之后变成了4 5 6 7 0 1 2现在给你一个数,让你输出其在数组中的索引,没找到的话输出-1。

class Solution {
public:
    int search(int A[], int n, int target) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int pivot=findP(A,n);
		int ret=binsearch(A,0,pivot,target);
		if(ret==-1)
			ret=binsearch(A,pivot+1,n-1,target);
		return ret;
	}
	int findP(int A[] , int n){
		int left=0; 
		int right=n-1;
		int middle=0;
		if(A[left]<A[right])
			return 0;
		while(left<=right){
			middle=((right-left)>>1)+left;
			if(A[middle]>A[left])
				left=middle;
			else if(A[middle]<A[left])
				right=middle;
			else
				return middle;
		}
		return middle;
	}
	int binsearch(int A[] , int left , int right , int target){
		while(left<=right){
			int middle=((right-left)>>1)+left;
			if(A[middle]<target)
				left=middle+1;
			else if(A[middle]>target)
				right=middle-1;
			else
				return middle;
		}
		return -1;
	}
};


你可能感兴趣的:([leetcode] Search in Rotated Sorted Array)