LeetCode 33. Search in Rotated Sorted Array

Description: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).

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

解题思路:题目的大概意思是,一个递增序列(不含重复数据)切成2半,前一半放到后面去组成新的序列,该序列有个特点,只有在分界点上递减,其他都是递增的。现在给定一个目标,找出该目标所在的位置,找不到返回-1。因为要求时间复杂度为O(log n),所有得使用二分法,当前数组可以使用二分法。如果mid的数据等于target,则立即返回mid。如果left到mid的数据是连续递增的,并且target在这个范围内,则在该范围内继续使用二分法,如果不在该范围内,则在mid到right使用二分法。如果left到mid数据不是连续递增的,说明在mid到right是连续递增的,如果target在mid到right范围内,则继续使用二分法,否则,在left到mid的范围内使用二分法。最后都找不到的话,返回-1。

参考代码:

int bin_search(int left, int right, vector<int> nums, int target) {
    //递归用if
    while (left <= right) {
        int mid = (left + right) / 2;
        if (target == nums[mid])
            return mid;
        if (nums[mid] >= nums[left] && target >= nums[left] && target < nums[mid]) {
            //return bin_search(left, mid - 1, nums, target);
            right = mid - 1;
        }
        else if (nums[mid] >= nums[left] && (target <= nums[left] || (target > nums[mid]))) {
            //return bin_search(mid + 1, right, nums, target);
            left = mid + 1;
        }
        else if (nums[mid] <= nums[left] && (target > nums[mid]) && target <= nums[right]) {
            //return bin_search(mid + 1, right, nums, target);
            left = mid + 1;
        }
        else {
            //return bin_search(left, mid-1, nums, target);
            right = mid - 1;
        }
        
    }
    return -1;
}
int MySolution::search(vector<int>& nums, int target) {
    return bin_search(0, nums.size() - 1, nums, target);
}

总结:最后发现递归和循环效率相差很大,这里给出测试结果
使用循环二分查找:
Runtime: 4 ms, faster than 81.73% of C++ online submissions for Search in Rotated Sorted Array.
Memory Usage: 8.9 MB, less than 43.37% of C++ online submissions for Search in Rotated Sorted Array.

使用递归二分查找:
Runtime: 8 ms, faster than 15.65% of C++ online submissions for Search in Rotated Sorted Array.
Memory Usage: 10.7 MB, less than 6.03% of C++ online submissions for Search in Rotated Sorted Array.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值