Leetcode 33 Search in Rotated Sorted Array

本文介绍了一种在逆转数组中进行二分查找的算法,该算法通过虚拟节点法找到旋转点,然后进行标准二分查找。文章提供了两种实现方法,并强调了算法的时间复杂度必须为O(log n)。

摘要生成于 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.

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

这个题目的意思是在一个逆转的数组中进行二分查找,使用的方法为虚拟节点(类似于一致性哈希中的虚拟节点),将虚拟节点映射到真实节点即可。

1)虚拟节点法

class Solution {
    public int search(int[] nums, int target) {
        int n = nums.length;
        int low = 0 , high = n - 1;
        while(low < high){//设置虚拟节点
            int mid = (low + high) / 2;
            if(nums[mid] > nums[high]){
                low = mid + 1;
            }else{
                high = mid;
            }
        }
        int rot = low;
        low = 0;
        high = n - 1;
        while(low <= high){
            int mid = (low + high) / 2;
            int real = (mid + rot) % n;//虚拟节点映射到真实的节点。
            if(nums[real] == target){
                return real;
            }else if(nums[real] < target){
                low = mid + 1;
            }else{
                high = mid - 1;
            }
        }
        return -1;
    }
}

2)

class Solution {
    public int search(int[] nums, int target) {
        int l=0;
        int h=nums.length-1;
        while(l<=h){
            int mid=(l+h)/2;
            int midValue=(nums[mid]<nums[0])==(target<nums[0])?nums[mid]:target<nums[0]?Integer.MIN_VALUE:Integer.MAX_VALUE;
            if(target==midValue){
                return mid;
            }else if(target>midValue){
                l=mid+1;
            }else{
                h=mid-1;
            }
        }
        return -1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值