let 33 Search in Rotated Sorted Array

本文介绍了一种在旋转后的有序数组中高效查找目标值的方法。通过分析旋转数组的特点,提出了一种利用二分查找的思想确定目标值位置的算法,并详细解释了如何通过数学换算找到目标值在旋转数组中的确切位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

主题思想: 这道题的关键是利用原先是有序数组,经过变换过来的,如果能够知道变换pivot 元素在原数组的下标,以及要查找target 在原数组的下标,很容易经过数学换算,一步得出target 在当前(由原数组变换后得到) 数组的下标。 而在有序数组中查找下边,可以log N 查找

所以要分析,已知pivot 元素在原数组,和target在原数组下标,如何换算得到target 在当前数组的下边。

很容易有个分析思路就是: pivot 下标和target 下边之间关系有三种:
1. 等于,这是pivot 变换后成为当前数组第一个元素,下标为0
2. target下标小于pivot 下标 ,则旋转后 n-pivot下标+target下标
3. target 下标大于pivot 下标,则旋转后,target下标-pivot下标

代码:

class Solution {
    public int search(int[] nums, int target) {

        if(nums==null||nums.length==0) return -1;

        int pivot=nums[0];

        Arrays.sort(nums);

        // find pivot and find the target
        int targetIndex=find(nums,target);
        if(targetIndex==-1) return -1;

        int pivotIndex=find(nums,pivot);

        if(pivotIndex==targetIndex) return 0;
        else if(pivotIndex<targetIndex) return targetIndex-pivotIndex;
        else return nums.length-pivotIndex+targetIndex;


    }
    public int find(int [] nums,int target){

        int low=0;
        int hi=nums.length-1;
        while(low<=hi){
            int mid=low+(hi-low)/2;

            if(target<nums[mid]){
                hi=mid-1;
            }else if(target>nums[mid]){
                low=mid+1;
            }else{
                return mid;
            }
        }

        return -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值