【LeetCode】3.Search in Rotated Sorted Array

题目描述(Medium)

Suppose an array sorted in ascending order 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.
Your algorithm's runtime complexity must be in the order of O(log n).

题目链接

https://leetcode.com/problems/search-in-rotated-sorted-array/description/

Example 1:

 Input: nums = [4,5,6,7,0,1,2], target = 0
 Output: 4

Example 2:

 Input: nums = [4,5,6,7,0,1,2], target = 3
 Output: -1

算法分析

二分查找,需要判断好左右边界,这里主要是先判断出递增子序列,然后以递增子序列作为判断条件,确定左右边界。

提交代码:

class Solution {
public:
	int search(vector<int>& nums, int target) {
		if (nums.empty()) return -1;

		int beg = 0, end = nums.size() - 1;
		int mid;

		while (beg <= end)
		{
			mid = (beg + end) / 2;
			if (nums[mid] == target) 
				return mid;

			if (nums[mid] >= nums[beg])
			{
				if (target >= nums[beg] && target < nums[mid])
					end = mid - 1;
				else
					beg = mid + 1;
			}
			else
			{
				if (target > nums[mid] && target <= nums[end])
					beg = mid + 1;
				else
					end = mid - 1;
			}
		}

		return -1;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& nums, int target, int expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	int result = s.search(nums, target);

	if (result == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{

	// 典型输入,单调升序的数组的一个旋转
	vector<int> array1 = { 3, 4, 5, 1, 2 };
	Test("Test1", array1, 1, 3);

	// 单调升序数组,旋转0个元素,也就是单调升序数组本身
	vector<int> array2 = { 1, 2, 3, 4, 5 };
	Test("Test2", array2, 4, 3);

	// 数组中只有一个数字
	vector<int> array3 = { 2 };
	Test("Test3", array3, 2, 0);

	// 输入nullptr
	vector<int> array4;
	Test("Test4", array4, 1, -1);

	vector<int> array5 = { 4, 5, 6, 7, 0, 1, 2 };
	Test("Test5", array5, 0, 4);

	vector<int> array6 = { 5, 1, 3 };
	Test("Test6", array6, 5, 0);

	vector<int> array7 = { 4, 5, 6, 7, 8, 1, 2, 3 };
	Test("Test7", array7, 8, 4);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/81564112