leetcode 33 Search in Rotated Sorted Array

You are given an integer array nums sorted in ascending order, and an integer target.

Suppose that nums 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]).

If target is found in the array return its index, otherwise, return -1.

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
Example 3:

Input: nums = [1], target = 0
Output: -1

Constraints:

1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
All values of nums are unique.
nums is guranteed to be rotated at some pivot.
-10^4 <= target <= 10^4

链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array

解题思路:

采用二分查找寻找value为target的元素。

因为,数组是递增顺序,可以以某个pivot进行旋转,旋转后的两个子数组也分别是递增的序列。

所以,采用二分法查找时,如果nums[mid] == target,则说明找到了,就返回下标index。

否则,比较nums[first]和nums[mid]的大小,如果nums[first] <= nums[mid],说明从first到mid是递增序列,如果target的值,刚好在这个递增序列内,last = mid,否则target如果不在这个递增序列内,就说明first的值要更新了,first = mid + 1。

如果nums[first] > nums[mid],就说明first到mid并不是一个递增序列,它肯定是旋转后的两个序列的交叉情况,这时候,从nums[mid]到nums[last-1]就是递增序列,判断,如果target在这个序列内,则first = mid+1,否则更新last = mid即可。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int first = 0;
        int last = nums.size();
        while(first < last)
        {
            const int mid = first + (last - first) / 2;
            if(nums[mid] == target)
            {
                return mid;
            }
            if(nums[first] <= nums[mid])
            {
                if(target >= nums[first] && target < nums[mid])
                {
                    last = mid;
                }
                else
                {
                    first = mid + 1;
                }
            }
            else
            {
                if(target > nums[mid] && target <= nums[last-1])
                {
                    first = mid + 1;
                }
                else
                {
                    last = mid;
                }
            }
        }
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值