Search rotation sorted array (search-in-rotated-sorted-array)

Search rotation sorted array (search-in-rotated-sorted-array)

Suppose ascending order according to the array was rotated in a previously unknown point.
(For example, the array [0,1,2,4,5,6,7]may become [4,5,6,7,0,1,2]).
Searching for a given target value, if the existence of the target array, its index returns, otherwise it returns -1.
You can assume that the array element does not exist in duplicate.

Your time complexity of the algorithm must be O (log n) level.

Example 1:

输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4

Example 2:

输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1

Code and ideas

The array is divided into two, one of which must be ordered, and the other may be ordered, it can be partially ordered. At this section, look for an orderly dichotomy. And then divided into two portions disorder, wherein a certain order, another possible order, may be disordered. So the cycle.

#include <stdio.h>
#include <vector>

class Solution {
public:
    int search(std::vector<int>& nums, int target) {
    	int begin = 0;
		int end = nums.size() - 1;
		while(begin <= end){
			int mid = (begin + end) / 2;
			if (target == nums[mid]){
				return mid;
			}
			else if (target < nums[mid]){
				if (nums[begin] < nums[mid]){
					if (target >= nums[begin]){
						end = mid - 1;
					}
					else{
						begin = mid + 1;
					}
				}
				else if (nums[begin] > nums[mid]){
					end = mid -1;
				}
				else if (nums[begin] == nums[mid]){
					begin = mid + 1;
				}
			}
			else if (target > nums[mid]){
				if (nums[begin] < nums[mid]){
					begin = mid + 1;
				}
				else if (nums[begin] > nums[mid]){
					if (target >= nums[begin]){
						end = mid - 1;
					}
					else{
						begin = mid + 1;
					}
				}
				else if (nums[begin] == nums[mid]){
					begin = mid + 1;
				}
			}
		}
		return -1;
    }
};

int main(){
	int test[] = {9, 12, 15, 20, 1, 3, 6, 7};
	std::vector<int> nums;
	Solution solve;
	for (int i = 0; i < 8; i++){
		nums.push_back(test[i]);
	}
	for (int i = 0; i < 22; i++){
		printf("%d : %d\n", i, solve.search(nums, i));
	}
	return 0;
}

python3 Solution

class Solution:
    def search(self, nums: List[int], target: int) -> int:
            return nums.index(target) if target in nums else -1
Published 151 original articles · won praise 47 · Views 230,000 +

Guess you like

Origin blog.csdn.net/e891377/article/details/103792448