Skip to content

Latest commit

 

History

History
96 lines (83 loc) · 2.26 KB

0033 搜索旋转排序数组.md

File metadata and controls

96 lines (83 loc) · 2.26 KB

0033 搜索旋转排序数组

Question:

假设按照升序排序的数组在预先未知的某个点上进行了旋转。

( 例如,数组 [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

Solution:

class Solution {
    public int BS(int[] nums,int target,int low,int high){
        int mid;
        while(low<=high){
            mid=(low+high)/2;
            if(nums[mid]<target){
                low=mid+1;
            }else if(nums[mid]>target){
                high=mid-1;
            }else{
                return mid;
            }
        }
        return -1;
    }
    public int findBP(int[] nums){
        int cmp=nums[0];
        int low=1;
        int high=nums.length-1;
        int mid;
        while(low<=high){
            mid=(low+high)/2;
            if(nums[mid]<nums[mid-1]&&nums[mid]<nums[mid+1])
                return mid;
            else if(nums[mid]>nums[0])
                low=mid+1;
            else
                high=mid-1;
        }
        return -1;
    }
    public int search(int[] nums, int target) {
        int length=nums.length;
        if(length==0)
            return -1;
        if(length==1){
            if(nums[0]==target)
                return 0;
            else
                return -1;
        }
        if(nums[0]<nums[length-1])
            return BS(nums,target,0,length-1);
        else if(nums[length-1]<nums[length-2]){
            if(target<nums[length-1])
                return -1;
            else if(target==nums[length-1])
                return length-1;
            else
                return BS(nums,target,0,length-2);
        }
        else{
            int BP=findBP(nums);
            if(target>nums[0]){
                return BS(nums,target,1,BP-1);
            }else if(target<nums[0]){
                return BS(nums,target,BP,length-1);
            }else{
                return 0;
            }
        }
    }
}