题目:

假设按升序排序的数组在未知的某处旋转。(即[0,1,2,4,5,6,7]可能变为[4,5,6,7,0,1,2])。使用时间复杂度为O(logN)的方法查询数组内有没有target。

思路1:利用stl的map

int search(vector<int>& nums, int target) {//利用map,99%
	map<int,int> a, b;
	int temp = INT32_MIN;
	int i = 0, sz = nums.size();
	if (!sz)
		return -1;
	auto it = a.begin();
	for (; nums[i] > temp; ++i) {
		a.insert(pair<int, int>(nums[i], i));
		temp = nums[i];
	}
	for (; i < sz; ++i) {
		b.insert(pair<int, int>(nums[i], i));
	}

	if (target >= a.begin()->first ){
		if ((it = a.find(target)) != a.end())
			return it->second;
		else
			return -1;
	}
	else {
		if ((it = b.find(target)) != b.end())
			return it->second;
		else
			return -1;
	}
}

思路2:二分查找

int search(vector<int>& nums, int target) {//二分法
	int l = 0, r = nums.size() - 1, mid;
	while (l <= r) {
		mid = (r + l) / 2;
		if (nums[mid] == target)
			return mid;
			
		else if (nums[mid] < nums[r]) {//旋转位置在mid左边
			if (nums[mid] < target && target <= nums[r])
				l = mid + 1;
			else
				r = mid - 1;
		}
		
		else {//旋转位置在mid右边
			if (nums[mid] > target && target >= nums[l])
				r = mid - 1;
			else
				l = mid + 1;
		}
	}
	return -1;
}