LeetCode-Search in Rotated Sorted Array

本文介绍了一种在旋转排序数组中寻找特定元素的高效算法。该算法采用二分查找法,在保持O(logn)的时间复杂度下完成搜索。文章详细解释了不同旋转情况下的处理逻辑,并提供了一个Java实现示例。

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

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

题意:给定一个按照升序排列的数组,寻找指定元素的位置;需要注意的是这个数组可能在某一个地方旋转了,旋转的两个部分仍然是有序的;并且要求时间复杂度在O(log n);

解法:题目要求时间复杂度在O(log n),那么我们就不可能通过遍历一遍数组来找到这个元素,可以通过二分查找法来搜索,但是,现在的数组可能在任意一个地方发生旋转,导致整个数组时无序的;虽然数组被旋转了,数组中被旋转的两个部分仍然是有序的;对于数组[0,1,2,4,5,6,7]来说,一共有以下几种旋转方案:
1 2 4 5 6 7 0
2 4 5 6 7 0 1
4 5 6 7 0 1 2
5 6 7 0 1 2 4
6 7 0 1 2 4 5
7 0 1 2 4 5 6
0 1 2 4 5 6 7

  • if nums[mid] > nums[right] : 左边的序列是有序的
  • if nums[mid] < nums[right] : 右边的序列是有序的

无论哪一种情况,我们只需要判断目标元素是否在有序的那部分值的范围中,若不在,那必定是在另外一个部分;

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0){
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        int mid = (left + right) / 2;
        while(left <= right){
            if(nums[mid] == target){
                return mid;
            }
            else if(nums[mid] > nums[right]){
                if(target >= nums[left] && target < nums[mid]) right = mid - 1;
                else left = mid + 1;
            }//ordered int the left half
            else{
                if(target > nums[mid] && target <= nums[right]) left = mid + 1;
                else right = mid - 1;
            }//ordered in the right half
            mid = (left + right) / 2;
        }
        return -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值