【LeetCode】#33搜索旋转排序数组(Search in Rotated Sorted Array)

【LeetCode】#33搜索旋转排序数组(Search in Rotated Sorted Array)

题目描述

假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。

示例

示例 1:

输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4

示例 2:

输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1

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

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

解法

class Solution {
    public int search(int[] nums, int target) {
        if(nums.length<=0){
            return -1;
        }
        int len = nums.length, l=0, m=len/2, r=len-1;
        while(true){
            int left=nums[l], mid=nums[m], right=nums[r];
            if(target==left){
                return l;
            }
            if(target==mid){
                return m;
            }
            if(target==right){
                return r;
            }
            if(Math.abs(m-l)<=1 && Math.abs(m-r)<=1){
                return -1;
            }
            
            if(left<mid){
                if(left<target && target<mid){
                    r = m;
                    m = (l+r)/2;
                    continue;
                }else{
                    l = m;
                    m = (l+r)/2;
                    continue;
                }
            }
            
            if(mid<right){
                if(mid<target && target<right){
                    l = m;
                    m = (l+r)/2;
                    continue;
                }else{
                    r = m;
                    m = (l+r)/2;
                    continue;
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84798888